.Net core 上傳檔案
阿新 • • 發佈:2020-12-29
#region 上傳檔案 /// <summary> /// 上傳檔案(上傳到專案中),返回儲存地址(儲存檔案資料夾+儲存檔名稱) /// </summary> /// <returns></returns> public JsonResult Upload(IFormFile file) { var currentDate = DateTime.Now; var webRootPath = hostingEnvironment.WebRootPath;//獲取專案路徑 try { var filePath = $"/UploadFile/{currentDate:yyyyMMdd}/"; //建立每日儲存資料夾 if (!Directory.Exists(webRootPath + filePath)) { Directory.CreateDirectory(webRootPath + filePath); }if (file != null) { //檔案字尾 var fileExtension = Path.GetExtension(file.FileName);//獲取檔案格式,拓展名 var fileSize = file.Length; //判斷檔案大小 if (fileSize > 1024 * 1024 * 10) //10M TODO:(1mb=1024X1024b) {return new JsonResult(new { isSuccess = false, resultMsg = "上傳失敗,檔案大小超過範圍" }); } //儲存的檔名稱(以名稱和儲存時間命名) var name = file.FileName.Substring(0, file.FileName.LastIndexOf('.')); var saveName = name + "_" + currentDate.ToString("HHmmss") + fileExtension; //檔案儲存 using (var fs = System.IO.File.Create(webRootPath + filePath + saveName)) { file.CopyTo(fs); fs.Flush(); } //完整的檔案路徑 var completeFilePath = Path.Combine(filePath, saveName); return new JsonResult(new { isSuccess = true, returnMsg = "上傳成功", completeFilePath = completeFilePath }); } else { return new JsonResult(new { isSuccess = false, resultMsg = "上傳失敗,未檢測上傳的檔案資訊~" }); } } catch (Exception ex) { return new JsonResult(new { isSuccess = false, resultMsg = "檔案儲存失敗,異常資訊為:" + ex.Message }); } } #endregion