在线文件下载
using System.IO;
using System.Net;
using System.Collections.Generic;
using ICSharpCode.SharpZipLib.Zip;
1.对多个文件进行下载:
经过修改的ICSharpCode.SharpZipLib.dll:
https://files.cnblogs.com/pingyangcst/SrcSamples修改过.rar
用法:
public void Download(IEnumerable<string> files, string zipFileName, string ServerFilePath)
{
//根据所选文件打包下载
MemoryStream ms = new MemoryStream();
byte[] buffer = null;
using (ZipFile file = ZipFile.Create(ms))
{
file.BeginUpdate();
foreach (var item in files)
{
file.Add(HttpContext.Current.Server.MapPath(ServerFilePath) + item);
}
file.CommitUpdate();
buffer = new byte[ms.Length];
ms.Position = 0;
ms.Read(buffer, 0, buffer.Length);
}
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + zipFileName);
HttpContext.Current.Response.BinaryWrite(buffer);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
调用
List<string> files = new List<string>();
files.Add(filename);// 可以添加多项
MyNameTransfom.Download(files, "Test.zip", "~/DownLoadPath/");
2. 下载单个文件
public static void DownLoadFile(string ServerFilePath)
{
// string s = HttpContext.Current.Request.PhysicalApplicationPath;
string filePath = HttpContext.Current.Server.MapPath(ServerFilePath);
if (File.Exists(filePath))
{
FileInfo file = new FileInfo(filePath);
HttpContext.Current.Response.ContentEncoding =
System.Text.Encoding.GetEncoding("UTF-8");
//解决中文乱码
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpContext.Current.Server.UrlEncode(file.Name));
//解决中文文件名乱码
HttpContext.Current.Response.AddHeader("Content-length", file.Length.ToString());
HttpContext.Current.Response.ContentType = "appliction/octet-stream";
HttpContext.Current.Response.WriteFile(file.FullName);
HttpContext.Current.Response.End();
}
}
调用:
string TheFileName = "~/ DownLoadPath /" +FileName;
test.DownLoadFile(TheFileName);
以上代码在Windows 2003 +Visual 2008环境测试.

浙公网安备 33010602011771号