前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >ASP.netMVC文件下载

ASP.netMVC文件下载

作者头像
全栈程序员站长
发布2022-09-18 13:57:29
发布2022-09-18 13:57:29
7390
举报

大家好,又见面了,我是你们的朋友全栈君。

ASP.netMVC文件下载

ASP.netMVC下载文件一般有几种方法

第一种:超链接方法,直接指向目标文件地址;

  1. window.open(“”);
  2. 标签href=“”;

第二种:后台下载,但后台下载又有三种方式;

(1)返回filestream

public FileStreamResult download()

{

string fileName = “”;//客户端保存的文件名

string filePath = Server.MapPath(“”);//路径

return File(new FileStream(filePath, FileMode.Open), “text/plain”,

fileName);

}

其中:“text/plain”是文件MIME类型

(2)返回file

public FileResult download()

{

string filePath = Server.MapPath(“”);//路径

return File(filePath, “text/plain”, “”//是客户端保存的文件名字);

}

(3)TransmitFile方法

1 public void download()

2 {

3 string fileName = “”;//客户端保存的文件名

4 string filePath = Server.MapPath(“”);//路径

5 FileInfo fileinfo = new FileInfo(filePath);

6 Response.Clear(); //清除缓冲区流中的所有内容输出

7 Response.ClearContent(); //清除缓冲区流中的所有内容输出

8 Response.ClearHeaders(); //清除缓冲区流中的所有头

9 Response.Buffer = true; //该值指示是否缓冲输出,并在完成处理整个响应之后将其发送

10 Response.AddHeader(“Content-Disposition”, “attachment;filename=” + fileName);

11 Response.AddHeader(“Content-Length”,fileinfo.Length.ToString());

12 Response.AddHeader(“Content-Transfer-Encoding”, “binary”);

13 Response.ContentType = “application/unknow”; //获取或设置输出流的 HTTP MIME 类型

14 Response.ContentEncoding = System.Text.Encoding.GetEncoding(“gb2312”); //获取或设置输出流的 HTTP 字符集

15 Response.TransmitFile(filePath);

16 Response.End();

17 }

(4)Response分块下载

1 public void download()

2 {

3 string fileName = “”;//客户端保存的文件名

4 string filePath = Server.MapPath(“”);//路径

5 System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);

7 if (fileInfo.Exists == true)

8 {

9 const long ChunkSize = 102400;//100K 每次读取文件,只读取100K,这样可以缓解服务器的压力

10 byte[] buffer = new byte[ChunkSize];

11 Response.Clear();

12 System.IO.FileStream iStream = System.IO.File.OpenRead(filePath);

14 long dataLengthToRead = iStream.Length;//获取下载的文件总大小

15 Response.ContentType = “application/octet-stream”;

16 Response.AddHeader(“Content-Disposition”, “attachment; filename=” + HttpUtility.UrlEncode(fileName));

17 while (dataLengthToRead > 0 && Response.IsClientConnected)

18 {

19 int lengthRead = iStream.Read(buffer, 0, Convert.ToInt32(ChunkSize));//读取的大小

20 Response.OutputStream.Write(buffer, 0, lengthRead);

21 Response.Flush();

22 dataLengthToRead = dataLengthToRead – lengthRead;

23 }

24 Response.Close();

25 }

}

这篇文章对你有帮助吗?作为一名程序工程师,在评论区留下你的困惑或你的见解,大家一起来交流吧!

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/157837.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档