在用户操作界面,由用户选择需要下载的文件,系统根据所选文件,在服务器上创建用于存储所选文件的临时文件夹,将所选文件拷贝至临时文件夹。然后调用 RAR程序,对临时文件夹进行压缩,然后输出到客户端。最后删除临时文件夹。
二、代码实现
1、ASP.NET批量下载 核心代码
//遍历服务器指定文件夹下的所有文件
string path = "uploads/Image/";
string serverPath = Server.MapPath(path);
//创建临时文件夹
string tempName = DateTime.Now.ToString("yyyyMMddHHMMss");
string tempFolder = Path.Combine(serverPath, tempName);
Directory.CreateDirectory(tempFolder);
DirectoryInfo folder = new DirectoryInfo(serverPath);
foreach (FileInfo file in folder.GetFiles())
{
string filename = file.Name;
File.Copy(serverPath + "/" + filename, tempFolder + "/" + filename);
}
//ZKHelper.JSHelper.Alert("图片拷贝成功!");
//产生RAR文件,及文件输出
RARSave(tempFolder, tempName);
DownloadRAR(tempFolder + "
////" + tempName + ".rar");
/// <summary>
/// 下载生成的RAR文件
/// </summary>
private void DownloadRAR(string file)
{
FileInfo fileInfo = new FileInfo(file);
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "attachment;filename=" + fileInfo.Name);
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();
string tempPath = file.Substring(0, file.LastIndexOf("
////"));
//删除临时目录下的所有文件
DeleteFiles(tempPath);
//删除空目录
Directory.Delete(tempPath);
Response.End();
}