ASP.netMVC文件下載的幾種方法


第一種:最簡單的超鏈接方法,標簽的href直接指向目標文件地址,這樣容易暴露地址造成盜鏈,這里就不說了

第二種:后台下載

 

在后台下載中又可以細分為幾種下載方式

首先,在前台,我們需要一個標簽

Home為controller,download為action。

如果需要傳一些參數,可以:

 

在后台:

(1)返回filestream

復制代碼
public FileStreamResult download()
{
     string fileName = "aaa.txt";//客戶端保存的文件名
     string filePath = Server.MapPath("~/Document/123.txt");//路徑
     return File(new FileStream(filePath, FileMode.Open), "text/plain",   
     fileName);
}
復制代碼

其中:“text/plain”是文件MIME類型

 

(2)返回file

public FileResult download()
{
            string filePath = Server.MapPath("~/Document/123.txt");//路徑
            return File(filePath, "text/plain", "welcome.txt"); //welcome.txt是客戶端保存的名字
}

 

(3)TransmitFile方法

復制代碼
 1  public void download()
 2  {
 3       string fileName = "aaa.txt";//客戶端保存的文件名
 4       string filePath = Server.MapPath("~/Document/123.txt");//路徑
 5       FileInfo fileinfo = new FileInfo(filePath);
 6             Response.Clear();         //清除緩沖區流中的所有內容輸出
 7             Response.ClearContent();  //清除緩沖區流中的所有內容輸出
 8             Response.ClearHeaders();  //清除緩沖區流中的所有頭
 9             Response.Buffer = true;   //該值指示是否緩沖輸出,並在完成處理整個響應之后將其發送
10             Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
11             Response.AddHeader("Content-Length",fileinfo.Length.ToString());
12             Response.AddHeader("Content-Transfer-Encoding", "binary");
13             Response.ContentType = "application/unknow";  //獲取或設置輸出流的 HTTP MIME 類型
14             Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312"); //獲取或設置輸出流的 HTTP 字符集
15             Response.TransmitFile(filePath);
16             Response.End();
17  }
復制代碼

 

(4)Response分塊下載

復制代碼
 1 public void download()
 2 {
 3             string fileName = "aaa.txt";//客戶端保存的文件名
 4             string filePath = Server.MapPath("~/Document/123.txt");//路徑
 5 
 6             System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);
 7             if (fileInfo.Exists == true)
 8             {
 9                 const long ChunkSize = 102400;//100K 每次讀取文件,只讀取100K,這樣可以緩解服務器的壓力
10                 byte[] buffer = new byte[ChunkSize];
11 
12                 Response.Clear();
13                 System.IO.FileStream iStream = System.IO.File.OpenRead(filePath);
14                 long dataLengthToRead = iStream.Length;//獲取下載的文件總大小
15                 Response.ContentType = "application/octet-stream";
16                 Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName));
17                 while (dataLengthToRead > 0 && Response.IsClientConnected)
18                 {
19                     int lengthRead = iStream.Read(buffer, 0, Convert.ToInt32(ChunkSize));//讀取的大小
20                     Response.OutputStream.Write(buffer, 0, lengthRead);
21                     Response.Flush();
22                     dataLengthToRead = dataLengthToRead - lengthRead;
23                 }
24                 Response.Close();
25             }         
26 }
復制代碼

 

+ajax方法

要重點說說這個方法,ajax返回不了文件流,所以說用ajax調用上面任意一種后台方法都要出問題,下載不了文件。

所以,只能讓后台返回所需下載文件的url地址,然后調用windows.location.href。

 

優點:ajax可以傳好幾個參數(當然以json形式),傳100個都無所謂。你要是用的方法傳100得寫死。。。(公司需求,至少要傳100多個參數)

缺點:支持下載exe,rar,msi等類型文件。對於txt則會直接打開,慎用!對於其他不常用的類型文件則直接報錯。

        所以我的建議是得到多個參數,通過數據庫找到所有需要下載的文件然后壓縮打包,然后返回url下載。(你要是一個一個給用戶下,用戶都瘋了)

        那么問題又來了,C#怎么用代碼實現將本地的一些文件打包壓縮到服務器目錄下呢?這我不知道。

           因為你只是單純的放在目錄文件夾下沒有用的,我們平時在服務器某目錄下添加某一個文件都是右鍵,添加XXX項這樣,這樣才能真正的將文件放在服務器中。

           可是純代碼該怎么實現呢??

        * 可能的解決方法:先在項目目錄下放一個空的rar文件或者沒什么功能的exe,msi文件,然后在后台打包完一些文件后去替換它,不知道可行不。

            (1)首先清空原壓縮包中的內容

            (2)將文件壓縮到壓縮包中

            (3)返回 XXX.rar

 

前端:

"button" id="downloaon"/>

ajax:

復制代碼
$("#downloaon").click(function () {
                $.ajax({
                    type: "GET",
                    url: "/Home/download",
                    data: { id: "1" },
                    dataType:"json",
                    success: function (result) {
                        window.location.target = "_blank";
                        window.location.href = result;                      
                    }
                })
            })
復制代碼

后台:

public string download(int id)
{
            string filePath = "Document/123.msi";//路徑
            return filePath;
}

這里,id是沒有什么作用的,后台就別用什么server.Mappath了,肯定錯。直接寫服務器項目文件夾/文件名 即可。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM