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

供参考!

你可能感兴趣的:(MVC下载文件)