ASP.NET批量下载文件

一、实现步骤

  在用户操作界面,由用户选择需要下载的文件,系统根据所选文件,在服务器上创建用于存储所选文件的临时文件夹,将所选文件拷贝至临时文件夹。然后调用 RAR程序,对临时文件夹进行压缩,然后输出到客户端。最后删除临时文件夹。

二、代码实现

1、ASP.NET批量下载 核心代码

C# 代码   复制


//遍历服务器指定文件夹下的所有文件
            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) 方法

C# 代码   复制


/// <summary>
        /// 生成RAR文件
        /// </summary>
        /// <param name="path">存放复制文件的目录</param>
        /// <param name="rarPatch">RAR文件存放目录</param>
        /// <param name="rarName">RAR文件名</param>
        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)方法

C# 代码   复制


/// <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();
        }

4、DeleteFiles(string tempPath) 方法

C# 代码   复制


/// <summary>
        /// 删除临时目录下的所有文件
        /// </summary>
        /// <param name="tempPath">临时目录路径</param>
        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;
            }
        }
时间: 2024-08-04 17:29:33

ASP.NET批量下载文件的相关文章

ASP.NET批量下载服务器端指定目录文件

1 //遍历服务器指定文件夹下的所有文件 2 string path = "uploads/Image/"; 3 string serverPath = Server.MapPath(path); 4 5 //创建临时文件夹 6 string tempName = DateTime.Now.ToString("yyyyMMddHHMMss"); 7 string tempFolder = Path.Combine(serverPath, tempName); 8 D

&lt;&lt;&lt; JS实现网页批量下载文件,支持PC/手机

//把下载链接放入集合里 var downloadData = new Array{"http://www.empli.com/data1.apk","http://www.empli.com/data1.apk","http://www.empli.com/data1.apk","http://www.empli.com/data1.apk"}; var downloadNum=0;//方法执行次数 circularWind

php批量下载文件

最近用codeigniter开发一个图片网站,发现单文件下载很容易实现,批量下载的话,不是很容易实现. 以下是参考网上的例子,编写的一个测试文件,遇到同样问题而不知道如何处理的朋友们可以参考下. 思路: ① 把要下载的图片信息组合到$imgs数组中 ② 把要下载的图片打包成zip压缩包 ③ 下载压缩包,删除服务器上的临时zip文件 <?php $imgs[] = 'http://demo.pic.com/column_f/large/IMG_Af8P_15.jpg'; $imgs[] = 'ht

C#异步批量下载文件

C#异步批量下载文件 实现原理:采用WebClient进行批量下载任务,简单的模拟迅雷下载效果! 废话不多说,先看掩饰效果: 具体实现步骤如下: 1.新建项目:WinBatchDownload 2.先建一个Windows窗体:FrmBatchDownload,加载事件FrmBatchDownload_Load 3.放置一个Button按钮:btnStartDownLoad,单机事件btnStartDownLoad_Click 4.放置一个DataGridView:dgvDownLoad. 5.具

七牛云存储批量下载文件

public class UploadFile {         //设置好账号的ACCESS_KEY和SECRET_KEY      String ACCESS_KEY = "akey";      String SECRET_KEY = "skey";      //要上传的空间      String bucketname = "bucketname";//         //下载路径(空间里的外链复制过来)      String d

Python抓取网页&amp;批量下载文件方法初探(正则表达式+BeautifulSoup) (转)

Python抓取网页&批量下载文件方法初探(正则表达式+BeautifulSoup) 最近两周都在学习Python抓取网页方法,任务是批量下载网站上的文件.对于一个刚刚入门python的人来说,在很多细节上都有需要注意的地方,以下就分享一下我在初学python过程中遇到的问题及解决方法. 一.用Python抓取网页 基本方法: [python] view plaincopyprint? import urllib2,urllib url = 'http://www.baidu.com' req 

使用kettle批量下载文件

使用kettle批量下载文件 最新有项目中需要批量下载文件并把结果导入到数据中,通过一些实验测试,kettle确实可以胜任.问题是关键是如果通过http批量下载文件,本文将详细说明,假设你已经了解了kettle的基本知识,如果需要可以查看我的系列入门教程. 本文的示例代码可以在这里下载. 主作业 kettle的转换中没有通过http下载文件的步骤,但是job的有对应的步骤,所以在主job调用子job(Download.kjb),需要下载的文件列表通过一个转换提供. 文件列表转换 这里我仅仅使用数

asp.net mvc5 下载文件方法

控制器自带的 FileContentResult 可以让我们很方便的返回文件到服务端,减少了很多步骤.用于下载文件的时候,像视频.文本.图片这种浏览器支持的文件,默认就会被浏览器打开.这时候想让它变成下载,还需要设置一下响应头,告诉浏览器如何处理才行. public ActionResult DownLoadFile(String path, string fileName, string contentType) { Response.AddHeader("Content-Dispositio

[ASP.NET][C#]下载文件时中文文件名出现乱码

负责的网站在ASP.NET网页有一段下载Word/Excel文件的程序,最近使用者要求的文件名称内含繁体中文字, 同事用chrome/firefox浏览器测试下载都很正常显示,但用IE(版本11)开启时,却出现了乱码. 1.准备一个中文文件名的文件 ASP.NET MVC 2.在HomeControler中加入下载程序Download public ActionResult Download() { //文件位置 string filepath = @"E:testWebApplication1