本文介紹了一種在ASP.NET中下載文件的方法。
方法一:多是最簡單的、最短的方式:
1 Response.ContentType = "application/pdf"; 2 Response.AppendHeader("Content-Disposition", "attachment; filename=MyFile.pdf"); 3 Response.TransmitFile(Server.MapPath("~/Files/MyFile.pdf")); 4 Response.End();
第一步是設置文檔內容的類型,上面的例子是下載一個.PDF格式的文件。下面是最經常使用的一些文檔內容類型:html
方法二:解決.PDF文件較大時,可能致使所下載的PDF文件沒法打開的方案
1 protected void Button1_Click(object sender, EventArgs e) 2 { 3 string path; 4 try
5 { 6 path = Request.PhysicalApplicationPath + "/" + Session["pdfpath"].ToString() + "/PDF/" + Session["mlmc"].ToString() + ".pdf"; 7 } 8 catch (Exception) 9 { 10 return; 11 } 12 System.IO.Stream iStream = null; 13 byte[] buffer = new Byte[10000]; 14 int length; 15 long dataToRead; 16 string filename = Session["mlmc"].ToString() + ".pdf"; 17
18 try
19 { 20 iStream = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read); 21 dataToRead = iStream.Length; 22 Response.Clear(); 23 Response.ClearHeaders(); 24 Response.ClearContent(); 25 Response.ContentType = "application/pdf"; //文件類型
26 Response.AddHeader("Content-Length", dataToRead.ToString());//添加文件長度,進而顯示進度
27 Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8)); 28 while (dataToRead > 0) 29 { 30 if (Response.IsClientConnected) 31 { 32 length = iStream.Read(buffer, 0, 10000); 33 Response.OutputStream.Write(buffer, 0, length); 34 Response.Flush(); 35
36 buffer = new Byte[10000]; 37 dataToRead = dataToRead - length; 38 } 39 else
40 { 41 dataToRead = -1; 42 } 43 } 44
45 } 46 catch (Exception ex) 47 { 48 Response.Write("文件下載時出現錯誤!"); 49 } 50 finally
51 { 52 if (iStream != null) 53 { 54 iStream.Close(); 55 } 56 //結束響應,不然將致使網頁內容被輸出到文件,進而文件沒法打開
57 Response.End(); 58 } 59 }
經過以上代碼,可在瀏覽器中打開一個「打開/保存」對話框來下載並保存文件。