asp.net(c#)文件下载实现代码


复制代码 代码如下:

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);
*/
« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3