.net 根據路徑將本地檔案轉為流返回前端下載
阿新 • • 發佈:2022-05-23
.net Core中根據檔案路徑和名字將檔案轉為流返回給前端提供下載,需要傳入檔案路徑(不帶域名),和檔名稱(用於下載使用),前端使用<a></a>標籤來進行訪問下載,或者 location.href 來訪問
[ApiController] [Route("[controller]")] public class FilesController : ControllerBase { private readonly IWebHostEnvironment _webHostEnvironment;public FilesController(IWebHostEnvironment webHostEnvironment) { _webHostEnvironment = webHostEnvironment; } /// <summary> /// 獲取檔案流 /// </summary> /// <param name="url">檔案路徑</param> /// <param name="name">檔名稱</param> ///<returns></returns> [HttpGet] public async Task<IActionResult> UploadFile(string url,string name) { string webRootPath = _webHostEnvironment.WebRootPath; string contentRootPath = _webHostEnvironment.ContentRootPath; var str = url.Split('.');//獲取檔案字尾 var newpath = contentRootPath + "/wwwroot/" + url;//我這裡的url是/files/202205/xxx.txt;不帶域名,因為是netcore專案所以前面加上wwwroot FileStream fs = new FileStream(newpath, FileMode.OpenOrCreate, FileAccess.Read); byte[] vs = new byte[fs.Length]; while (true) { int r = fs.Read(vs, 0, vs.Length); string s = Encoding.UTF8.GetString(vs, 0, r); if (r == 0) { fs.Close(); break; } } return File(vs, "application/"+ str[1].ToString(), name+"."+ str[1].ToString()); } }
contentRoot是使用程式更目錄
ContentRoot: C:\MyApp\wwwroot
WebRoot: C:\MyApp\wwwroot\wwwroot
這裡建議使用contentRoot在後面加上/wwwroot/
讀到檔案之後將它放入byte數組裡面寫入流,防止有較大檔案所以上面使用while迴圈寫入