asp.net mvc实现文件下载

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

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

但是这个方法有他的缺陷:
1.下载的文件后缀必须为iis程序池中存在的文件
2.此方法是通过浏览器打开服务器文件,无法直接下载
近期看了asp.net 下载文件几种方式这篇文章并且结合了一些其他的文章之后,找到了更好的解决办法,我用的是 以字符流的形式下载文件
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标签,但是没找到好用的方法,只能暂时先隐藏掉
}

效果图:
在这里插入图片描述

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值