1. 程式人生 > 實用技巧 >.NETCore MVC 上傳圖片

.NETCore MVC 上傳圖片

1,前臺JavaScript

 1  function uploadImg() {
 2             var formDate = new FormData();
 3             var files = $("#image").get(0).files;
 4             //拼接請求引數
 5             formDate.append("image", files[0]);
 6             //如果有其他參需要一起提交到後臺
 7             //formDate.append("location", location);
 8
$.ajax({ 9 type: "POST", 10 url: "UploadImage", 11 contentType: false, 12 cache: false, 13 processData: false, 14 data: formDate, 15 error: function (request) { 16 17 },
18 success: function (data) { 19 $('#content').val(data); 20 } 21 }); 22 }
UploadImg

2,後臺C#程式碼

 1         /// <summary>
 2         /// 圖片上傳
 3         /// </summary>
 4         /// <returns></returns>
 5         public
string UploadImage() 6 { 7 var files = Request.Form.Files; 8 if (files.Count == 0) 9 { 10 return "File does not exist!"; 11 } 12 var file = files[0]; 13 string fileName = file.FileName; 14 if (string.IsNullOrEmpty(fileName))//伺服器是否存在該檔案 15 { 16 return "File does not exist!"; 17 } 18 // 獲取上傳的圖片名稱和副檔名稱 19 string fileFullName = Path.GetFileName(file.FileName); 20 string fileExtName = Path.GetExtension(fileFullName); 21 var fileExtNames = _Configuration["FileExtName"].Split(','); 22 if (!fileExtNames.Contains(fileExtName)) 23 { 24 return "File type error!"; 25 } 26 //獲取當前專案所在的物流路徑 27 string imgPath = _Configuration["ImgPath"]; 28 var newPath = fileFullName.Substring(0, fileFullName.IndexOf(fileExtName)) + System.DateTime.UtcNow.Ticks + fileExtName; 29 var src = imgPath + newPath; 30 31 // 如果目錄不存在則要先建立 32 if (!Directory.Exists(imgPath)) 33 { 34 Directory.CreateDirectory(imgPath); 35 } 36 using (FileStream fs = System.IO.File.Create(src)) 37 { 38 file.CopyTo(fs); 39 fs.Flush(); 40 } 41 return newPath; 42 }
UploadImage

3,appsettings.json

 1 {
 2   "Logging": {
 3     "LogLevel": {
 4       "Default": "Information",
 5       "Microsoft": "Warning",
 6       "Microsoft.Hosting.Lifetime": "Information"
 7     }
 8   },
 9   "AllowedHosts": "*",
10   "ImgPath": "D:\\Work\\Global Quality\\Morningstar.EquityFundamentals\\Morningstar.EquityFundamentals.WebApi\\wwwroot\\images\\",
11   "FileExtName": ".jpg,.png,.bmp"
12 }
appsettings.json

效果: