---------- 20210303 https://dotblogs.com.tw/kinanson/2017/06/03/004307 2017-06-03 [WEB API]下載檔案的幾種方式 [WEB API]下載檔案的幾種方式 前言 之前專案針對web api下載其實就有實做過,不過每次實做都要去看之前的專案,也是蠻麻煩的,乾脆紀錄在部落格,順便研究一下以前沒有的需求應該如何實做,希望能幫助到有需要的人,這邊的範例全部都是使用HttpResponseMessage的方式。 導覽 下載iis上的檔案 下載遠端的檔案 下載硬碟上的檔案 結論 下載iis上的檔案 public IHttpActionResult Download(string file) { var sourcePath = HttpContext.Current.Server.MapPath($@"~/File/{file}"); //取得server的相對路徑 if (!File.Exists(sourcePath)) { return ResponseMessage(new HttpResponseMessage(HttpStatusCode.Gone)); } var response = new HttpResponseMessage(HttpStatusCode.OK); var fileStream = new FileStream(sourcePath, FileMode.Open, FileAccess.Read); response.Content = new StreamContent(fileStream); response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); response.Content.Headers.ContentDisposition.FileName = HttpUtility.UrlPathEncode(file); response.Content.Headers.ContentLength = fileStream.Length; //告知瀏覽器下載長度 return ResponseMessage(response); } 下載遠端的檔案 public async Task DownloadUrl() { var url = "https://cn.vuejs.org/images/logo.png"; HttpClient client = new HttpClient(); var result = await client.GetAsync(url); var response = new HttpResponseMessage(HttpStatusCode.OK); var content = await result.Content.ReadAsStringAsync(); response.Content =new StringContent(content); response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); response.Content.Headers.ContentDisposition.FileName = HttpUtility.UrlPathEncode(Path.GetFileName(url)); response.Content.Headers.ContentLength = content.Length; //告知瀏覽器下載長度 return ResponseMessage(response); } 下載硬碟上的檔案 public async Task DownloadHd() { var path = @"C:\Users\anson\Downloads\2017-05-20.txt"; var response = new HttpResponseMessage(HttpStatusCode.OK); var stream = new FileStream(path, FileMode.Open, FileAccess.Read); response.Content = new StreamContent(stream); response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); response.Content.Headers.ContentDisposition.FileName = HttpUtility.UrlPathEncode(Path.GetFileName(path)); response.Content.Headers.ContentLength = stream.Length; //告知瀏覽器下載長度 return ResponseMessage(response); } 結論 這邊因為程式碼很簡單,也不知道要說明什麼,有些東西就是不知道怎麼做而已,知道一些關鍵點的其實都不難,其實還有另一種下載方式,就是用ftp的方式,不過這部份筆者懶得架設ftp,所以就不想紀錄了,而且網路上範例挺多的,就請讀者自行爬文囉,如果有任何錯誤或不好的地方,再請多多指教。