使用.net core搭建文件服務器

    標題之所以帶上.net core,而不是.net就是由於兩者在類庫的使用以及部署環境有很大的差別,所以特此說明。

    長話短說,直接開始!

    1.新建一個.net core項目,版本是2.0,爲了方便就建一個MVC模板項目

    

    2.安裝保存圖片必須的類庫,在NuGet裏搜索System.Drawing.Common,然後點安裝。值的說明一下,在.net裏,操作是引用System.Drawing.dll,雖然core裏也可以這麼引用並且代碼編譯能通過,但是實際運行的時候是會拋異常的。所以還是老老實實在NuGet裏安裝吧。

    

    3.接下來就是代碼部分,我們寫一個接收上傳文件的方法,上傳的原理是,將圖片轉成base64作爲參數傳遞

    接口方法如圖:

      

        /// <summary>
        /// 圖片上傳
        /// </summary>
        /// <param name="id">標識,暫時沒用</param>
        /// <param name="filename">圖片名稱,帶後綴名</param>
        /// <param name="img">圖片base64編碼</param>
        /// <returns></returns>
        public IActionResult Upload(int id, string filename, string img)
        {
            string res = string.Empty;
            try
            {
                string filePath = _hostingEnvironment.WebRootPath + "/images/" + filename;
                //將Base64String轉爲圖片並保存
                byte[] arr2 = Convert.FromBase64String(img);
                using (MemoryStream ms2 = new MemoryStream(arr2))
                {
                    System.Drawing.Bitmap bmp2 = new System.Drawing.Bitmap(ms2);
                    bmp2.Save(filePath, System.Drawing.Imaging.ImageFormat.Png);
                }
                res = "http://static.lovemoqing.com" + "/images/" + filename;
            }
            catch (Exception ex)
            {
                res = ex.ToString();
            }
            return Content(res);
        }
View Code

 

     _hostingEnvironment.WebRootPath這個路徑是獲取應用程序wwwroot文件夾用的,它是通過一個接口實現的,如下圖:

    

        private readonly IHostingEnvironment _hostingEnvironment;

        public HomeController(IHostingEnvironment hostingEnvironment)
        {
            _hostingEnvironment = hostingEnvironment;
        }
View Code

 

    就這3步,接口端的就完成了,將項目部署到服務器上即可,同時解析一下域名,這裏我自己的項目解析的是static.lovemoqing.com,完成以後返回網頁路徑即可。


    下面說一下如何調用:

    

      上傳端是一個傳統的表單提交操作,將上傳的圖片轉成base64編碼,然後通過WebClient調用接口,傳遞參數,得到返回值,也就是線上圖片路徑。

        [HttpPost]
        public string UpdateInfoImages()
        {
            string res = "";
            for (int i = 0; i < Request.Files.Count; i++)
            {
                HttpPostedFileBase file = Request.Files[i];
                string fileName = System.IO.Path.GetFileName(file.FileName);
                if (fileName == "") continue;
                string fileExtension = System.IO.Path.GetExtension(fileName);
                System.IO.Stream stream = file.InputStream;
                byte[] bytes = new byte[stream.Length];
                stream.Read(bytes, 0, bytes.Length);
                stream.Seek(0, System.IO.SeekOrigin.Begin);
                string ImageData = Convert.ToBase64String(bytes);
                res = PostImage(1024, ImageData, fileName);
            }
           
            return res;
        }
        public static string PostImage(int id, string ImageData, string filename)
        {
            System.Net.WebClient WebClientObj = new System.Net.WebClient();
            System.Collections.Specialized.NameValueCollection PostVars = new System.Collections.Specialized.NameValueCollection();
            PostVars.Add("img", ImageData);
            PostVars.Add("id", id.ToString());
            PostVars.Add("filename", filename);
            string Newurl = "http://static.lovemoqing.com/Home/Upload";
            byte[] byRemoteInfo = WebClientObj.UploadValues(Newurl, "POST", PostVars);
            return System.Text.Encoding.Default.GetString(byRemoteInfo);
        }
View Code

 

    


    以上就是全部的源碼實現了。反正也沒人看,就先不發佈在首頁,這塊寫得有些粗糙,畢竟是案例,等後面寫相關的demo的時候再加入到裏面。

    相關參數:

    服務器:centos7

    項目版本:.net core 2.0


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章