一、在MVC中的下载方法

/// <summary>
/// 文件载入
/// </summary>
/// <returns></returns>
[GET("LoadFile/PdfObjectLoadFile")]<br />public ActionResult PdfObjectLoadFile() 
{
    string f = ReadPdfFilePath(Request.QueryString["FileID"], EnumHelper.StringToEnum<PdfFileEnum>(Request.QueryString["PdfFile"]));
    if (string.IsNullOrEmpty(f)) 
    {
        return Content("文件不存在!");
    }
    string fname = Request.QueryString["FileName"];
    if (string.IsNullOrEmpty(fname)) 
    {
        fname = "文件查看";
    }
    return File(f, "application/pdf", HttpUtility.UrlEncode(fname + ".pdf"));
}
  • 一开始使用的是FilePathResult,可是有些文件类型会无法识别,导致另存为后没有后缀,
  • 使用HttpUtility.UrlEncode编码,防止文件名称中文乱码

以下二到五参考博文:http://www.cnblogs.com/zhaopei/p/download.html

二、Response.BinaryWrite

public void FileDownload()
 {
     string fileName = "测试文件.rar";
     string filePath = Server.MapPath("/TempData/测试文件.rar");//要被下载的文件路径   

     Response.ContentType = "application/octet-stream";//二进制流
     //通知浏览器下载文件而不是打开  
     Response.AddHeader("Content-Disposition", "attachment;  filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));

     //以字符流的形式下载文件  
     using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
     {
         Response.AddHeader("Content-Length", fs.Length.ToString());
         //这里容易内存溢出
         //理论上数组最大长度 int.MaxValue 2147483647 ,实际分不到那么多,会搞死服务器
         byte[] bytes = new byte[(int)fs.Length];
         fs.Read(bytes, , bytes.Length);
         Response.BinaryWrite(bytes);
     }
     Response.Flush();
     Response.End();
 }

三、Response.WriteFile

public void FileDownload()
{
    string fileName = "测试文件.rar";//客户端保存的文件名  
    string filePath = Server.MapPath("/TempData/测试文件.rar");//要被下载的文件路径  
    FileInfo fileInfo = new FileInfo(filePath);
    Response.Clear();
    Response.ClearContent();
    Response.ClearHeaders();
    Response.AddHeader("Content-Disposition", "attachment;filename=\"" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8) + "\"");
    Response.AddHeader("Content-Length", fileInfo.Length.ToString());//文件大小
    Response.AddHeader("Content-Transfer-Encoding", "binary");
    Response.ContentType = "application/octet-stream";
    Response.WriteFile(fileInfo.FullName);//大小参数必须介于零和最大的 Int32 值之间(也就是最大2G,不过这个操作非常耗内存,也会搞死服务器)
    //这里容易内存溢出
    Response.Flush();
    Response.End();
}

四、Response.OutputStream.Write(循环读取)

public void FileDownload()
{
    string fileName = "测试文件.rar";//客户端保存的文件名  
    string filePath = Server.MapPath("/TempData/测试文件.rar");//要被下载的文件路径   

    if (System.IO.File.Exists(filePath))
    {
        const long ChunkSize = ; //100K 每次读取文件,只读取100K,这样可以缓解服务器的压力  
        byte[] buffer = new byte[ChunkSize];

        Response.Clear();
        using (FileStream fileStream = System.IO.File.OpenRead(filePath))
        {
            long fileSize = fileStream.Length; //文件大小  
            Response.ContentType = "application/octet-stream"; //二进制流
            Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
            Response.AddHeader("Content-Length", fileStream.Length.ToString());//文件总大小
            while (fileSize >  && Response.IsClientConnected)//判断客户端是否还连接了服务器
            {
                //实际读取的大小  
                int readSize = fileStream.Read(buffer, , Convert.ToInt32(ChunkSize));
                Response.OutputStream.Write(buffer, , readSize);
                Response.Flush();//如果客户端 暂停下载时,这里会阻塞。
                fileSize = fileSize - readSize;//文件剩余大小
            }
        }
        Response.Close();
    }
}

五、Response.TransmitFile(最好方法)

将指定的文件直接写入 HTTP 响应输出流,而不在内存中缓冲该文件。

public void FileDownload5()
{          
    //前面可以做用户登录验证、用户权限验证等。

    string filename = "测试文件.rar";   //客户端保存的文件名  
    string filePath = Server.MapPath("/TempData/测试文件.rar");//要被下载的文件路径 

    Response.ContentType = "application/octet-stream";  //二进制流
    Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);
    Response.TransmitFile(filePath); //将指定文件写入 HTTP 响应输出流
}