程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> ASP.NET >> ASP.NET基礎 >> asp.net(c#)文件下載實現代碼

asp.net(c#)文件下載實現代碼

編輯:ASP.NET基礎
復制代碼 代碼如下:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e) { }
//TransmitFile實現下載
protected void Button1_Click(object sender, EventArgs e)
{
/* 微軟為Response對象提供了一個新的方法TransmitFile來解決使用Response.BinaryWrite 下載超過400mb的文件時導致Aspnet_wp.exe進程回收而無法成功下載的問題。 代碼如下: */
Response.ContentType = "application/x-zip-compressed"; Response.AddHeader("Content-Disposition", "attachment;filename=z.zip");
string filename = Server.MapPath("DownLoad/z.zip"); Response.TransmitFile(filename);
}
//WriteFile實現下載
protected void Button2_Click(object sender, EventArgs e)
{
/* using System.IO; */
string fileName = "asd.txt";//客戶端保存的文件名
string filePath = Server.MapPath("DownLoad/aaa.txt");//路徑
FileInfo fileInfo = new FileInfo(filePath);
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName); Response.AddHeader("Content-Length", fileInfo.Length.ToString());
Response.AddHeader("Content-Transfer-Encoding", "binary");
Response.ContentType = "application/octet-stream";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
Response.WriteFile(fileInfo.FullName);
Response.Flush();
Response.End();
}
//WriteFile分塊下載
protected void Button3_Click(object sender, EventArgs e)
{
string fileName = "aaa.txt";//客戶端保存的文件名
string filePath = Server.MapPath("DownLoad/aaa.txt");//路徑
System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);
if (fileInfo.Exists == true)
{
const long ChunkSize = 102400;//100K 每次讀取文件,只讀取100K,這樣可以緩解服務器的壓力
byte[] buffer = new byte[ChunkSize];
Response.Clear();
System.IO.FileStream iStream = System.IO.File.OpenRead(filePath);
long dataLengthToRead = iStream.Length;//獲取下載的文件總大小
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName)); while (dataLengthToRead > 0 && Response.IsClientConnected)
{
int lengthRead = iStream.Read(buffer, 0, Convert.ToInt32(ChunkSize));//讀取的大小 Response.OutputStream.Write(buffer, 0, lengthRead);
Response.Flush();
dataLengthToRead = dataLengthToRead - lengthRead;
}
Response.Close();
}
}
//流方式下載
protected void Button4_Click(object sender, EventArgs e)
{
string fileName = "aaa.txt";//客戶端保存的文件名
string filePath = Server.MapPath("DownLoad/aaa.txt");//路徑 //以字符流的形式下載文件
FileStream fs = new FileStream(filePath, FileMode.Open);
byte[] bytes = new byte[(int)fs.Length]; fs.Read(bytes, 0, bytes.Length);
fs.Close();
Response.ContentType = "application/octet-stream"; //通知浏覽器下載文件而不是打開 Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
}

/*
這裡提供4種常用下載方式 以供參考導讀:   
本文通過一個實例向大家介紹用C#進行Internet通訊編程的一些基本知識。我們知道.Net類包含了請求/響應層、應用協議層、傳輸層等層次。在本程序中,我們運用了位於請求/響應層的WebRequest類以及WebClient類等來實現高抽象程度的Internet通訊服務。本程序的功能是完成網絡文件的下載。   
實現原理
程序實現的原理比較簡單,主要用到了WebClient類和FileStream類。其中WebClient類處於System.Net名字空間中,該類的主要功能是提供向URI標識的資源發送數據和從URI標識的資源接收數據的公共方法。我們利用其中的DownloadFile()方法將網絡文件下載到本地。然後用FileStream類的實例對象以數據流的方式將文件數據寫入本地文件。這樣就完成了網絡文件的下載。   
實現步驟   
首先,打開Visual Studio.Net,新建一個Visual C#Windows應用程序的工程,不妨命名為“MyGetCar”。接著,布置主界面。我們先往主窗體上添加如下控件:兩個標簽控件、兩個文本框控件、一個按鈕控件以及一個狀態欄控件。
設置各控件屬性如下:   
控件類型 控件名稱 屬性類型 屬性值 主窗體 Form1 Text屬性 文件下載器 標簽控件 Label1 Text屬性 文件地址: TextAlign屬性 MiddleRight Label2 Text屬性 另存到: TextAlign屬性 MiddleRight 文本框控件 srcAddress Text屬性 (空) tarAddress Text屬性 (空) 按鈕控件 Start FlatStyle屬性 Flat Text屬性 開始下載 狀態欄控件 StatusBar Text屬性 (空)   
其他屬性可為默認值,最終的主窗體如下圖所示:         
完成主窗體的設計,我們接著完成代碼的編寫。   
在理解了基本原理的基礎上去完成代碼的編寫是相當容易。程序中我們主要用到的是WebClient類,不過在我們調用WebClient類的實例對象前,我們需要用WebRequest類的對象發出對統一資源標識符(URI)的請求。
復制代碼 代碼如下:
try { WebRequest myre=WebRequest.Create(URLAddress); }
catch(WebException exp){
MessageBox.Show(exp.Message,"Error");
}

這是一個try-catch語句,try塊完成向URI的請求,catch塊則捕捉可能的異常並顯示異常信息。其中的URLAddress為被請求的網絡主機名。   在請求成功後,我們就可以運用WebClient類的實例對象中的DownloadFile()方法實現文件的下載了。其函數原型如下:   public void DownloadFile( string address, string fileName);   其中,參數address為從中下載數據的 URI,fileName為要接收數據的本地文件的名稱。   之後我們用OpenRead()方法來打開一個可讀的流,該流完成從具有指定URI的資源下載數據的功能。其函數原型如下:   public Stream OpenRead(string address);   其中,參數address同上。   最後就是新建一個StreamReader對象從中讀取文件的數據,並運用一個while循環體不斷讀取數據,只到讀完所有的數據。   
還有在使用以上方法時,你將可能需要處理以下幾種異常:   
● WebException:下載數據時發生錯誤。   
● UriFormatException:通過組合 BaseAddress、address 和 QueryString 所構成的 URI 無效。   
這部分的代碼如下:(client為WebClient對象,在本類的開頭處聲明即可)
復制代碼 代碼如下:
statusBar.Text = "開始下載文件...";
client.DownloadFile(URLAddress,fileName);
Stream str = client.OpenRead(URLAddress);
StreamReader reader = new StreamReader(str);
byte[] mbyte = new byte[100000];
int allmybyte = (int)mbyte.Length;
int startmbyte = 0;
statusBar.Text = "正在接收數據...";
while(allmybyte>0){
int m = str.Read(mbyte,startmbyte,allmybyte);
if(m==0)
break;
startmbyte+=m;
allmybyte-=m;
}

完成了文件數據的讀取工作後,我們運用FileStream類的實例對象將這些數據寫入本地文件中:
FileStream fstr = new FileStream(Path,FileMode.OpenOrCreate,FileAccess.Write); fstr.Write(mbyte,0,startmbyte);
*/
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved