风清月

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

电脑版发表于:2020/3/16 11:53

使用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


关于TNBLOG
TNBLOG,技术分享。技术交流:群号677373950
ICP备案 :渝ICP备18016597号-1
App store Android
精彩评论
{{item.replyName}}
{{item.content}}
{{item.time}}
{{subpj.replyName}}
@{{subpj.beReplyName}}{{subpj.content}}
{{subpj.time}}
猜你喜欢