private HttpResponseMessage ExportData(string ids, Func<string,string> exportFunc,string dataNotExistsMsg) { var filePath = exportFunc.Invoke(ids); // 檢查檔案是否存在 if (!File.Exists(filePath)) { return Request.CreateResponse(HttpStatusCode.NotFound, new BaseResponseDto() { Message = $"{dataNotExistsMsg}" }); } HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK); try { var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read); response.Content = new StreamContent(stream); response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");//這裡可以改為通用的application/octet-stream,表示下載的是二進位制的流。如果改為 png/pdf 瀏覽器會自動開啟不展示下載 response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = Path.GetFileName(filePath) }; response.Content.Headers.ContentLength = stream.Length; } catch { response = new HttpResponseMessage(HttpStatusCode.InternalServerError); } return response; }
另外,如果配置了swagger ,使用swagger去除錯下載檔案介面,那麼下載的檔案會無法開啟,提示檔案錯誤,且下載的檔案大小和原始檔大小不一致,不知道是swagger哪裡出了問題,但是如果直接用瀏覽器訪問url下載,下載所得的檔案大小又和原始檔一樣大,而且可以正常開啟 。