asp.net mvc实现文件下载

编程入门 行业动态 更新时间:2024-10-10 04:26:36

asp.net mvc实现<a href=https://www.elefans.com/category/jswz/34/1771438.html style=文件下载"/>

asp.net mvc实现文件下载

前段时间一直对如何解决文件下载的问题比较困惑,对文件下载的问题一直都是用的前端的方式解决的,代码如下

//下载
function download(filePath) {window.open(filePath);
}

但是这个方法有他的缺陷:
1.下载的文件后缀必须为iis程序池中存在的文件
2.此方法是通过浏览器打开服务器文件,无法直接下载
近期看了asp 下载文件几种方式这篇文章并且结合了一些其他的文章之后,找到了更好的解决办法,我用的是 以字符流的形式下载文件
Controller源码:

[HttpGet]
public ActionResult Download(string filePath) {filePath = Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["AttachmentPath"] + filePath);string fileName = Path.GetFileName(filePath);FileStream fs = new FileStream(filePath, FileMode.Open);byte[] bytes = new byte[(int)fs.Length];   //以字符流的形式下载文件fs.Read(bytes, 0, bytes.Length);fs.Close();Response.Charset = "UTF-8";Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");Response.ContentType = "application/octet-stream";  //通知浏览器下载文件而不是打开Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(fileName));Response.BinaryWrite(bytes);Response.Flush();Response.End();return new EmptyResult();
}

View源码:

//下载
function download(getur) {//getur = "/控制器/方法名?filePath=" + 文件相对路径;var str = document.createElement("a");//创建a标签str.href = getur;document.body.appendChild(str);str.click();str.style.display = "none";//隐藏标签//ps:本想删除a标签,但是没找到好用的方法,只能暂时先隐藏掉
}

效果图:

更多推荐

asp.net mvc实现文件下载

本文发布于:2024-02-07 12:32:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1757000.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   asp   net   mvc

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!