• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
我只吃饭不洗碗
博客园    首页    新随笔    联系   管理    订阅  订阅
.net 4.8 webApi 文件下载部分代码记录
 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下载,下载所得的文件大小又和源文件一样大,而且可以正常打开 。

posted on 2024-05-21 13:39  我只吃饭不洗碗  阅读(81)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3