文件打包为zip格式文件下载

整个思路是这样的:

1.查询数据库中的文件流放到datatable中
2.循环datatable将文件流一个个生成文件,放到对应的文件夹中,
3.下载某个文件夹下的所有文件
a.循环这个文件夹下的所有文件,调用zip()方法压缩到zipSteam中
b.将zipStream流保存为一个.zip文件
4.返回给前端压缩成功
5.前端用window.open(“压缩文件.zip”)下载压缩文件

这个程序是几年前写的,比较绕,不是个最佳方法,应该有更好的。

优化思路:

1.将数据库中查询出来的文件流直接调用zip()方法压缩到zipSteam,然后将zipSteam压缩文件流直接输出给前端,这样优化后才是最好的做法,待优化

 private void DownLaodZip2017(HttpContext context)
        {

                ZipFloClass zc = new ZipFloClass();

                string res_str = context.Request.Form["list"].ToString();
                //string res_str = "2,4,6";
                string[] data = res_str.Split(‘,‘);
                OunamesFilesToFiles(data);
                for (int i = 0; i < data.Length; i++)
                {
                    string doc_path = context.Server.MapPath("~/ProjectMgt/Doc2017") + "\\" + data[i].Trim() + "\\";
                    string zip_path = context.Server.MapPath("~/ProjectMgt/Doc2017/zip/zip") + "\\" + data[i].Trim() + ".zip";
                    if (Directory.Exists(doc_path))
                    {
                        zc.ZipFile(doc_path, zip_path);
                    }

                }
                string zip_Path = context.Server.MapPath("~/ProjectMgt/Doc2017/zip/zip");
                string zip_Name = context.Server.MapPath("~/ProjectMgt/Doc2017/zip/打包数据.zip");
                if (File.Exists(zip_Name))
                {
                    File.Delete(zip_Name);
                }

                zc.ZipFile(zip_Path, zip_Name);

                string[] paths = Directory.GetFiles(zip_Path);
                for (int n = 0; n < paths.Length; n++)
                {
                    File.Delete(paths[n]);
                }
                context.Response.Write("{success:true, files:‘生成文件成功‘}");

        }

        private void DownLaodZip(HttpContext context)
        {
            if (context.Request["type"] != null)
            {

                ZipFloClass zc = new ZipFloClass();
                string type = context.Request["type"].ToString();
                switch (type)
                {
                    case "rc": type = "常规"; break;
                    case "ic": type = "工控"; break;
                    case "lp": type = "等保"; break;
                }
                string res_str = context.Request.Form["list"].ToString();
                //string res_str = "2,4,6";
                string[] data = res_str.Split(‘,‘);
                for (int i = 0; i < data.Length; i++)
                {
                    string doc_path = context.Server.MapPath("~/ProjectMgt/Doc") + "\\" + data[i].Trim() + "\\" + type;
                    string zip_path = context.Server.MapPath("~/ProjectMgt/Doc/zip/zip") + "\\" + data[i].Trim() + ".zip";
                    if (Directory.Exists(doc_path))
                    {
                        zc.ZipFile(doc_path, zip_path);
                    }

                }
                string zip_Path = context.Server.MapPath("~/ProjectMgt/Doc/zip/zip");
                string zip_Name = context.Server.MapPath("~/ProjectMgt/Doc/zip/打包数据.zip");
                if (File.Exists(zip_Name))
                {
                    File.Delete(zip_Name);
                }

                zc.ZipFile(zip_Path, zip_Name);

                string[] paths = Directory.GetFiles(zip_Path);
                for (int n = 0; n < paths.Length; n++)
                {
                    File.Delete(paths[n]);
                }
                context.Response.Write("{success:true, files:‘生成文件成功‘}");

                #region
                //List<string> downloadurl = new List<string>();
                //ExtFacade ef = new ExtFacade();
                //for (int i = 0; i < data.Length; i++) {
                //    string query = string.Format(@"select top 1 t.LoadUrl from
                //    tbl_Net_SecurityCheck t
                //    where t.OUID in(
                //     select t.OUID from tbl_Base_OUInfo t where substring (OUCode,0,21)in
                //     (
                //      select m.OUCode from tbl_Base_OUInfo m
                //      where m.OUID=‘{0}‘)
                //    )
                //    and t.DocType=‘{1}‘ order by t.SubmitTime desc", data[i],type);
                //    DataTable dt = ef.GetBySQLText(query);
                //    downloadurl.Add(dt.Rows[0]["LoadUrl"].ToString());
                //}
                #endregion
            }
        }

		private void OunamesFilesToFiles(string[] OUNAMES)
        {
            for (int i = 0; i < OUNAMES.Length; i++)
            {
                var dt= GetContentByOuname(OUNAMES[i]);
                DataTableToFiles(dt, OUNAMES[i]);
            }
        }
        private void DataTableToFiles(DataTable dt,string OUName)
        {
            string LoadUrl = HttpContext.Current.Server.MapPath("~/ProjectMgt/Doc2017") + "\\" + OUName;
            if (Directory.Exists(LoadUrl))
            {
                Directory.Delete(LoadUrl, true);
            }
            Directory.CreateDirectory(LoadUrl);
            for (int i=0;i<dt.Rows.Count;i++)
            {
                ToFile(dt.Rows[i]["OUName"].ToString(), (byte[])dt.Rows[i]["Content"], dt.Rows[i]["DownLoadFileName"].ToString());
            }
        }
        private void ToFile(string OUName, byte[] Content, string DownLoadFileName)
        {
            string LoadUrl = HttpContext.Current.Server.MapPath("~/ProjectMgt/Doc2017") + "\\" + OUName + "\\"+ DownLoadFileName;

            MemoryStream m = new MemoryStream(Content);
            FileStream fs = new FileStream(LoadUrl, FileMode.OpenOrCreate);
            m.WriteTo(fs);
            m.Close();
            fs.Close();
            m = null;
            fs = null;

        }

		/// <summary>
    /// 压缩文件类
    /// </summary>
    public class ZipFloClass
    {
        /// <summary>
        /// 压缩方法
        /// </summary>
        /// <param name="strFile"></param>
        /// <param name="strZip"></param>
        public void ZipFile(string strFile, string strZip)
        {
            if (strFile[strFile.Length - 1] != Path.DirectorySeparatorChar)
                strFile += Path.DirectorySeparatorChar;
            ZipOutputStream s = new ZipOutputStream(File.Create(strZip));
            s.SetLevel(6); // 0 - store only to 9 - means best compression
            zip(strFile, s, strFile);
            s.Finish();
            s.Close();
        }
        /// <summary>
        /// 压缩
        /// </summary>
        /// <param name="strFile"></param>
        /// <param name="s"></param>
        /// <param name="staticFile"></param>
        private void zip(string strFile, ZipOutputStream s, string staticFile)
        {
            if (strFile[strFile.Length - 1] != Path.DirectorySeparatorChar) strFile += Path.DirectorySeparatorChar;
            Crc32 crc = new Crc32();
            string[] filenames = Directory.GetFileSystemEntries(strFile);
            foreach (string file in filenames)
            {

                if (Directory.Exists(file))
                {
                    zip(file, s, staticFile);
                }

                else // 否则直接压缩文件
                {
                    //打开压缩文件
                    FileStream fs = File.OpenRead(file);

                    byte[] buffer = new byte[fs.Length];
                    fs.Read(buffer, 0, buffer.Length);
                    string tempfile = file.Substring(staticFile.LastIndexOf("\\") + 1);
                    ZipEntry entry = new ZipEntry(tempfile);

                    entry.DateTime = DateTime.Now;
                    entry.Size = fs.Length;
                    fs.Close();
                    crc.Reset();
                    crc.Update(buffer);
                    entry.Crc = crc.Value;
                    s.PutNextEntry(entry);

                    s.Write(buffer, 0, buffer.Length);
                }
            }
        }

    }

	private void DownLoad2017(HttpContext context)
        {
            string zip_Path = context.Server.MapPath("~/ProjectMgt/Doc2017/zip/zip");
            string zip_Name = context.Server.MapPath("~/ProjectMgt/Doc2017/zip/打包数据.zip");

            //zip_Name = context.Server.MapPath("~/ProjectMgt/Doc/安徽销售公司/常规/2016年网络安全检查-常规安全-准备阶段-安徽销售公司.xls");
            FileStream fs = new FileStream(zip_Name, FileMode.Open);
            byte[] bytes = new byte[(int)fs.Length];
            fs.Read(bytes, 0, bytes.Length);
            fs.Close();
            context.Response.ContentType = "application/octet-stream";
            //通知浏览器下载文件而不是打开
            context.Response.AddHeader("Content-Disposition", "attachment;  filename=" + HttpUtility.UrlEncode("打包数据.zip", System.Text.Encoding.UTF8));
            context.Response.BinaryWrite(bytes);
            context.Response.Flush();
            File.Delete(zip_Name);
            context.Response.End();
        }

js代码:
		Ext.Ajax.request({
                        url: ‘Ashx/NetCheckViewAll.ashx?flag=DownLoad2017‘,
                        method: ‘post‘,
                        async:false,
                        params: {
                            list: Ids
                        },
                        success: function (response, opts) {
                            //var url = ‘Ashx/NetCheckViewAll.ashx?flag=downzip‘;
                            //window.open(url);

                            Ext.Msg.confirm("下载", "确定要下载选中项吗?", function (button) {
                                if (button == "yes") {
                                    var url = ‘Ashx/NetCheckViewAll.ashx?flag=downzip2017‘;
                                    window.open(url);
                                }
                            });

                        }

                        //failure: function (response, opts) {
                        //    console.log(‘server-side failure with status code ‘ + response.status);
                        //}
                    });

  

原文地址:https://www.cnblogs.com/liuqiyun/p/9405619.html

时间: 2024-08-01 18:27:18

文件打包为zip格式文件下载的相关文章

java批量下载,将多文件打包成zip格式下载

现在的需求的: 根据产品族.产品类型,下载该产品族.产品类型下面的pic包: pic包是zip压缩文件: t_product表: 这些包以blob形式存在另一张表中: t_imagefile表: 现在要做的是:将接入网.OLT下面的两个包downloadPIC:MA5800系列-pic.zip 和 MA5900-pic.rar一起打包成zip压缩文件下载下来: 代码: ProductController.java: /** * 根据产品族.产品类型下载照片包 */ @RequestMapping

【转】C#打包文件夹成zip格式

原文地址 C#打包文件夹成zip格式(包括文件夹和子文件夹下的所有文件)C#打包zip文件可以调用现成的第三方dll,事半功倍,而且该dll完全免费,下载地址:SharpZipLib下载完解压缩后,把 ICSharpCode.SharpZipLib.dll 拷贝到当前项目的目录下(如果偷懒的话,可以直接拷贝到当前项目的bin\Debug目录下),在VS打开的项目引用上右键添加引用 ICSharpCode.SharpZipLib.dll然后,在VS打开的项目上右键新建一个类,命名为 ZipHelp

多文件打包下载以及单文件下载

今天项目中需要多文件打包下载和单文件下载的功能,以下做一些总结. 原代码: 1 package com.hlbj.utils; 2 3 import java.io.File; 4 import java.io.FileInputStream; 5 import java.io.FileOutputStream; 6 import java.io.InputStream; 7 import java.io.OutputStream; 8 import java.util.ArrayList; 9

Java—将文件打包为zip压缩文件

import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipE

文件打包(.zip)并返回打压缩包存放路径

1.由于公司需要将一个或多个视频进行打包,格式如下图: 2.创建zipUtil工具包: 1 package com.seegot.util; 2 3 import java.io.BufferedOutputStream; 4 import java.io.File; 5 import java.io.FileInputStream; 6 import java.io.FileOutputStream; 7 import java.io.InputStream; 8 import java.ut

python—txt文件转py文件再转ZIP格式

一.  创建新的txt文本: 二.  编写代码并另存为,转成py文件: 三.  转成ZIP格式     原文地址:https://www.cnblogs.com/xiaobai-yemao/p/8594532.html

列出zip文件内全部内容 当前目录下的所有文件压缩成zip格式的文件(file.zip)

[[email protected] Desktop]# zip -r image.zip ./*.jpg adding: 20161007_113743.jpg (deflated 0%) adding: 20161007_114943.jpg (deflated 0%) [[email protected] Desktop]# file image.zip image.zip: Zip archive data, at least v2.0 to extract [[email protec

目录下获取指定后缀文件打包成zip文件

file_dir = os.path.abspath('.') + "/MarkCoin" def zip_ya(): L = [] for root, dirs, files in os.walk(file_dir): for file in files: if os.path.splitext(file)[1] == '.png' or os.path.splitext(file)[1] == '.xlsx': L.append(file) z = zipfile.ZipFile(

PHP扩展类ZipArchive实现压缩解压Zip文件和文件打包下载 &amp;&amp; Linux下的ZipArchive配置开启压缩

PHP ZipArchive 是PHP自带的扩展类,可以轻松实现ZIP文件的压缩和解压,使用前首先要确保PHP ZIP 扩展已经开启,具体开启方法就不说了,不同的平台开启PHP扩增的方法网上都有,如有疑问欢迎交流.这里整理一下常用的示例供参考. 一.解压缩zip文件 ? 1 2 3 4 5 6 7 8 9 10 11 $zip = new ZipArchive;//新建一个ZipArchive的对象 /* 通过ZipArchive的对象处理zip文件 $zip->open这个方法的参数表示处理的