一、实现步骤
公司主营业务:做网站、网站建设、移动网站开发等业务。帮助企业客户真正实现互联网宣传,提高企业的竞争能力。创新互联建站是一支青春激扬、勤奋敬业、活力青春激扬、勤奋敬业、活力澎湃、和谐高效的团队。公司秉承以“开放、自由、严谨、自律”为核心的企业文化,感谢他们对我们的高要求,感谢他们从不同领域给我们带来的挑战,让我们激情的团队有机会用头脑与智慧不断的给客户带来惊喜。创新互联建站推出定远免费做网站回馈大家。
在用户操作界面,由用户选择需要下载的文件,系统根据所选文件,在服务器上创建用于存储所选文件的临时文件夹,将所选文件拷贝至临时文件夹。然后调用 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");
2、RARSave(string tempFolder, string tempName) 方法
////// 生成RAR文件 /// /// 存放复制文件的目录 /// RAR文件存放目录 /// RAR文件名 private void RARSave(string rarPatch, string rarName) { string the_rar; RegistryKey the_Reg; Object the_Obj; string the_Info; ProcessStartInfo the_StartInfo; Process the_Process; try { the_Reg = Registry.ClassesRoot.OpenSubKey(@"WinRAR"); the_Obj = the_Reg.GetValue(""); the_rar = the_Obj.ToString(); the_Reg.Close(); the_rar = the_rar.Substring(1, the_rar.Length - 7); the_Info = " a " + rarName + " -r"; the_StartInfo = new ProcessStartInfo(); the_StartInfo.FileName = "WinRar";//the_rar; the_StartInfo.Arguments = the_Info; the_StartInfo.WindowStyle = ProcessWindowStyle.Hidden; //打包文件存放目录 the_StartInfo.WorkingDirectory = rarPatch; the_Process = new Process(); the_Process.StartInfo = the_StartInfo; the_Process.Start(); the_Process.WaitForExit(); the_Process.Close(); } catch (Exception) { throw; } }
3、DownloadRAR(string file)方法
////// 下载生成的RAR文件 /// private void DownloadRAR(string file) { FileInfo fileInfo = new FileInfo(file); Response.Clear(); Response.ClearContent(); Response.ClearHeaders(); Response.AddHeader("Content-Disposition", "p_w_upload;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(); }
4、DeleteFiles(string tempPath) 方法
////// 删除临时目录下的所有文件 /// /// 临时目录路径 private void DeleteFiles(string tempPath) { DirectoryInfo directory = new DirectoryInfo(tempPath); try { foreach (FileInfo file in directory.GetFiles()) { if (file.Attributes.ToString().IndexOf("ReadOnly") != -1) { file.Attributes = FileAttributes.Normal; } File.Delete(file.FullName); } } catch (Exception) { throw; } }