1. 程式人生 > >.Net Core 檔案上傳與下載

.Net Core 檔案上傳與下載

參考連結:

遇到的問題:

  1. 按 參考1 中測試,下載檔案檔名總是變成方法名(DownloadFile),並且沒有副檔名,儲存後改副檔名可正常檢視。
  2. 參考 連結3 測試無效,未解決下載問題。
  3. 參考 連結2,問題解決。
    程式碼實現如下:

檔案上傳

[HttpPost]
public async Task<ActionResult> UploadFile()
{
   _folder = $@"{env.WebRootPath}\Upload";//env 可通過Controller的引數傳入,並取得:IHostingEnvironment _env
    string controller = RouteData.Values["controller"
].ToString(); var dirPath = _folder + $"/Template/{controller}"; if (!Directory.Exists(dirPath)) { Directory.CreateDirectory(dirPath); } var size = Request.Form.Files.Sum(f => f.Length); IFormFile file = Request.Form.Files.FirstOrDefault(); if (file.Length > 0
) { var filePath = $@"{dirPath}\{file.FileName}"; using (var stream = new FileStream(filePath, FileMode.Create)) { await file.CopyToAsync(stream);//寫入到伺服器。 } } _controllername = RouteData.Values["controller"].ToString(); string Id = Request.Form["Id"
].First(); var path = $"/api/{_controllername}/Detail/{Id}"; var data = _excelTemplateDocService.Get(path).Result.FirstOrDefault(); if(data!=null) { data.ExcelPath = file.FileName; path = $"/api/{_controllername}"; await _excelTemplateDocService.Post(path, data); } else { return BadRequest("ExcelPath未更新!"); } return Ok(new { code = 200, message = "success" }); }

檔案下載


[HttpGet]
public async Task<IActionResult> DownloadFile(string fileName)
{
    if (string.IsNullOrEmpty(fileName))
    {
        return NotFound();
    }
    string controller = RouteData.Values["controller"].ToString();
    var path = _folder + $"/Template/{controller}/{fileName}";
    var memoryStream = new MemoryStream();
    using (var stream = new FileStream(path, FileMode.Open))
    {
        await stream.CopyToAsync(memoryStream);
    }
    memoryStream.Seek(0, SeekOrigin.Begin);
    //檔名必須編碼,否則會有特殊字元(如中文)無法在此下載。
    string encodeFilename = msSystem.Web.HttpUtility.UrlEncode(fileName, msSystem.Text.Encoding.GetEncoding("UTF-8"));
    Response.Headers.Add("Content-Disposition", "attachment; filename=" + encodeFilename);
    return new FileStreamResult(memoryStream, "application/octet-stream");//檔案流方式,指定檔案流對應的ContenType。
}