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下载,下载所得的文件大小又和源文件一样大,而且可以正常打开 。
标签:webApi,stream,filePath,HttpResponseMessage,4.8,new,net,response,下载 From: https://www.cnblogs.com/INetIMVC/p/18203827