tnblog
首页
视频
资源
登录
愿你出走半生,归来仍是少年
排名
6
文章
6
粉丝
16
评论
8
{{item.articleTitle}}
{{item.blogName}} : {{item.content}}
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2024TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
欢迎加群交流技术

.net core使用response下载文件,下载excel

7343人阅读 2020/3/16 11:53 总访问:1601922 评论:0 收藏:0 手机
分类: net core

使用response下载文件:

using (FileStream fs = new FileStream(filePath, FileMode.Open))
{
    byte[] bytes = new byte[(int)fs.Length];
    fs.Read(bytes, 0, bytes.Length);
    fs.Close();
    //Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
    Response.ContentType = "application/octet-stream;charset=UTF-8";;
    string newName = Guid.NewGuid().ToString().Replace("-", "");
    Response.Headers.Add("Content-Disposition", "attachment; filename=" + newName + "." + tnblogResourceDTO.Suffix);
    Response.BodyWriter.WriteAsync(bytes);
    Response.BodyWriter.FlushAsync();
}

可以直接返回return file来下载文件

private readonly IWebHostEnvironment _webHostEnvironment;
public PhoneController(IWebHostEnvironment webHostEnvironment)
{
    _webHostEnvironment = webHostEnvironment;
}
public IActionResult DownloadFile()
{
    var filePath = "/app/tnblog_beta.apk";
    var fileName = "tnblog_beta.apk";
    /* FileStream fs = new FileStream(_webHostEnvironment.WebRootPath + filePath, FileMode.OpenOrCreate);
                fs.Close();*/
    return File(new FileStream(_webHostEnvironment.WebRootPath + filePath, FileMode.Open), 
    "application/octet-stream", fileName);
}



使用response
下载excel

//把内存流做为文件下载中转
MemoryStream memoryStream = new MemoryStream();
workbook.Write(memoryStream);

//Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
Response.ContentType = "application/octet-stream;charset=UTF-8"; ;
string newName = Guid.NewGuid().ToString().Replace("-", "");

Response.Headers.Add("Content-Disposition", "attachment;filename=" + WebUtility.UrlEncode("用户信息表.xls"));
//Response.Headers.Add("Content-Disposition", "attachment;filename=用户信息表.xls");
Response.BodyWriter.WriteAsync(memoryStream.ToArray());
Response.BodyWriter.FlushAsync();

这里下载名称做了一下url编码不然遇到中文下载会报错:InvalidOperationException: Invalid non-ASCII or control character in header: 0x7528


欢迎加群讨论技术,群:677373950(满了,可以加,但通过不了),2群:656732739

评价