流方式下载文件

Posted zhangzhang1118

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了流方式下载文件相关的知识,希望对你有一定的参考价值。

public ActionResult DownLoadAttachment(string attachmentId)
{
Attachment attachment = _customerInfoService.GetAttachment(attachmentId);
if (attachment != null)
{
try
{
string fileName = attachment.FileName;
string filePath = attachment.Path;
string fileType = attachment.FileType;
#region 流方式下载文件
Encoding encoding;
string outputFileName = null;
fileName = fileName.Replace("‘", "");

string browser = Request.UserAgent.ToUpper();
if (browser.Contains("MS") == true && browser.Contains("IE") == true)
{
outputFileName = HttpUtility.UrlEncode(fileName);
encoding = Encoding.Default;
}
else if (browser.Contains("FIREFOX") == true)
{
outputFileName = fileName;
encoding = Encoding.GetEncoding("GB2312");
}
else
{
outputFileName = HttpUtility.UrlEncode(fileName);
encoding = Encoding.Default;
}
FileStream fs = new FileStream(filePath, FileMode.Open);
long length = fs.Length;
byte[] bytes = new byte[(int)fs.Length];
fs.Read(bytes, 0, bytes.Length);
fs.Close();
Response.Charset = "UTF-8";
Response.ContentType = "application/octet-stream";
Response.ContentEncoding = encoding;
Response.AddHeader("Content-Disposition", "attachment; filename=" + outputFileName);
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
return new EmptyResult();
#endregion
}
catch (Exception ex)
{
return Content(string.Format("附件下载失败!错误信息:{0}", ex.Message));
}

}
else
{
return Content("附件不存在!");
}
}

以上是关于流方式下载文件的主要内容,如果未能解决你的问题,请参考以下文章

Vue.js使用Blob的方式实现excel表格的下载(流文件下载)

springboot:各种下载文件的方式

poi 制作 excel 并且以文件流的方式 传输到客户端下载

如何使用输出流或任何有效的方式将数据保存到文件中?

Vue 采用blob下载后端返回的excel流文件乱码问题

文件下载