zoukankan      html  css  js  c++  java
  • MVC下载文件

     public ActionResult Download(string url,string fileName)
            {
                if (!url.Contains("UploadFiles")) //保证是从这个文件目录下载
                {
                    return Content("下载路径不正确!");
                }
                var filePath = Server.MapPath(url);
                if (System.IO.File.Exists(filePath))  //判断文件是否存在
                {
                    try
                    {
                        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();
                    }
                    catch (Exception ex)
                    {
    
                        return Content("下载失败,"+ex.Message);
                    }
                    
                }
                else
                {
                    return Content("文件路径不存在!");
                }
                return new EmptyResult();
            }
    


    其实最开始图省事是直接打开url的形式,但是浏览器对一些后缀文件有限制,所以就写了此段下载的代码。

    供参考!

  • 相关阅读:
    python中创建实例属性
    Python中if __name__ == "__main__": 的理解
    模块
    python函数式编程
    python-复杂生成式
    生成器的测试
    mysql乱码配置
    javascript
    Sql Server 2008 R2 下载地址
    Microsoft Data Access Components 2.8
  • 原文地址:https://www.cnblogs.com/sunShineJing/p/5159885.html
Copyright © 2011-2022 走看看