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下載,下載所得的文件大小又和源文件一樣大,而且可以正常打開 。
浙公網安備 33010602011771號