• 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的形式,但是浏览器对一些后缀文件有限制,所以就写了此段下载的代码。

    供参考!

  • 相关阅读:
    SVN补充
    java面试资料总结
    JAVABEAN EJB POJO区别
    Hibernate使用原生sql语句
    Discrete Logging(poj 2417)
    卡牌游戏(bzoj 3191)
    Activation(hdu 4089)
    Aeroplane chess(hdu 4405)
    LOOPS(hdu 3853)
    巧克力(zoj 1363)
  • 原文地址:https://www.cnblogs.com/sunShineJing/p/5159885.html
Copyright © 2020-2023  润新知