mvc实现下载功能

来源:互联网 发布:php生成二维码代码 编辑:程序博客网 时间:2024/06/08 10:03


1、在后台写下载的代码,这里我放的位置是homecontroller.cs控制器文件中:

public ActionResult DownFile(string filePath, string fileName)
        {
            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).Replace("+","%20"));
            Response.BinaryWrite(bytes);
            Response.Flush();
            Response.End();
            return new EmptyResult();
        }

备注:红色部分是因为浏览器把空格处理为+,如果不加红色部分的代码,则显示下载的文件名中的空格都会是+。%20是为了让浏览器识别,显示正常的空格。

2、点击页面上的提交按钮,在处理那个页面的后台函数里调用上面的下载函数即可实现下载。

下载是用浏览器自带的下载,无需自己再多加处理。

1 0
原创粉丝点击