C# - 文件下载
- 文件分块下载
- 原理
每次只读取一部分文件流,如100k到缓冲区,使用flush()将缓冲区的内容刷新到文件中。 - 代码
- 原理
public void Download(filePath){
filePath=Server.MapPath(filePath);; //要下载的文件路径
string fileName = "downloadfile.txt";//客户端将要保存的文件名
const long Size = 102400;//缓冲区大小100K ,每次读取文件,只读取100K,缓解服务器的压力
byte[] buffer = new byte[Size];
FileStream stream = null;
try{
stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);//打开文件
Response.Clear();
long fileSize= stream.Length ;//获取下载的文件总大小
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName));
while (fileSize> 0 && Response.IsClientConnected)
{
int lengthRead=stream.Read(buffer,0,Convert.ToInt32(Size));//读取的大小
Response.OutputStream.Write(buffer, 0, lengthRead);
Response.Flush();
fileSize= fileSize- lengthRead;
}
}
catch(Exception ex){
Response.Write("下载失败:" + ex.Message);
}
finally{
if (stream != null)
{
stream.Close();
}
Response.Close();
}
}
- 从ftp文件服务器上分块下载文件
- 原理
先从ftp服务器上读取部分文件流到缓冲区,然后再使用flush()函数将缓冲区的文件刷新到文件中。 - 代码
FTPHelper中的下载方法
- 原理
/// <summary>
/// 文件下载
/// </summary>
/// <param name="buffer">缓冲区</param>
/// <param name="Size">读取文件大小</param>
/// <param name="URIpath">ftp文件路径</param>
/// <returns></returns>
public int DownLoadFile(byte[] buffer, long Size, string URIpath)
{
FtpWebRequest ftp;
int lengthRead = 0;
try
{
ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri(URIpath));
ftp.Method = WebRequestMethods.Ftp.DownloadFile;
ftp.UseBinary = true;
ftp.Credentials = new NetworkCredential(ConfigureHelper.getConfigKey("ftpUserName"), ConfigureHelper.getConfigKey("ftpPassword"));
FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
Stream ftpStream = response.GetResponseStream();
lengthRead = ftpStream.Read(buffer, 0, Convert.ToInt32(Size));
ftpStream.Close();
response.Close();
}
catch (Exception e)
{
}
return lengthRead;
}
controller方法
public void Download(filePath){
string fileName = "downloadfile.txt";//客户端将要保存的文件名
const long Size = 102400;//缓冲区大小100K ,每次读取文件,只读取100K,缓解服务器的压力
byte[] buffer = new byte[Size];
try{
Response.Clear();
long fileSize= getFileSize();//获取下载的文件总大小
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName));
while (fileSize > 0 && Response.IsClientConnected)
{
int lengthRead = FTPClientHelper.ftp.DownLoadFile(buffer, Size , filePath);//读取的大小
Response.OutputStream.Write(buffer, 0, lengthRead);
Response.Flush();
fileSize= fileSize- lengthRead;
}
}
catch(Exception ex){
Response.Write("下载失败:" + ex.Message);
}
finally{
Response.Close();
}
}