精华内容
下载资源
问答
  • 应业务需求,需要将打印出的pdf打包成压缩包,在网上找了很多个压缩工具,最终找到了一个合适使用的。(多个pdf打包) 直接贴上代码: package com.iShift.kachaexport.util; import java.io.File; import java.io...

    应业务需求,需要将打印出的pdf打包成压缩包,在网上找了很多个压缩工具,最终找到了一个合适使用的。(多个pdf打包)

    直接贴上代码:
    
    package com.iShift.kachaexport.util;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipOutputStream;
    
    public class ZIPUtil {
        
        public static String createZipFile(ArrayList<String> fileList, String zipFileName) {
            //构建压缩文件File
            File zipFile = new File(zipFileName);
            //初期化ZIP流
            ZipOutputStream out = null;
    
            try{
                //构建ZIP流对象
                out = new ZipOutputStream(new FileOutputStream(zipFile));
                //循环处理传过来的集合
                for(int i = 0; i < fileList.size(); i++){
                    //获取目标文件
                    File inFile = new File(fileList.get(i));
                    if(inFile.exists()){
                         //定义ZipEntry对象
                         ZipEntry entry = new ZipEntry(inFile.getName());
                         //赋予ZIP流对象属性
                         out.putNextEntry(entry);
                         int len = 0 ;
                         //缓冲
                         byte[] buffer = new byte[1024];
                         //构建FileInputStream流对象
                         FileInputStream fis;
                         fis = new FileInputStream(inFile);
                         while ((len = fis.read(buffer)) > 0) {
                             out.write(buffer, 0, len);
                             out.flush();
                         }
                         //关闭closeEntry
                         out.closeEntry();
                         //关闭FileInputStream
                         fis.close();
                    }
                }
            }catch (IOException e) {
                e.printStackTrace();
            }finally{
                 try {
                     //最后关闭ZIP流
                     out.close();
                 } catch (IOException e) {
                     e.printStackTrace();
                 }
            }
    
    
            return zipFileName;
    
        }
    }
    

    流程介绍:将多个文件名已“,”进行分割,分别获取其转换为pdf的地址,
    将地址加入进list集合中,并用工具包进行压缩,再上传至7牛,
    返回下载地址并返还至前端。

    ServiceImpl层:

    @Override
    	public String exportStudentPdfZip(String[] us, int subjectId, String beginDate, String endDate, Integer practise) throws Exception {
    		ArrayList<String> list = new ArrayList<>();
    		String uuid = UUIDUtil.genUUID();
    		String filePath = Constants.TEMP_FILE_PATH + "/" + uuid + ".zip";
    		for (String userIdStr : us) {
    			Long userId = DataTypeUtil.toLong(userIdStr);
    			String path = productDateRangPdfA41(userId, subjectId, beginDate, endDate, practise);
    			list.add(path);
    		}
    		ZIPUtil.createZipFile(list, filePath);
    		byte[] file2byte = file2byte(new File(filePath));
    		storeToQiniu(file2byte, uuid + ".zip");
    		return Constants.FILE_SERVER + uuid + ".zip";
    	}
    
    

    Controller层:

    @RequestMapping("/exportStudentPdf")
        public Response<?> exportStudentPdf(@RequestParam(value="userIds")String userIds, @RequestParam(value="beginDate")String beginDate, @RequestParam(value="endDate")String endDate
        										, @RequestParam(value="subjectId")int subjectId, @RequestParam(value="practise", required=false, defaultValue="1")Integer practise){
        	try {
        		String[] us = userIds.split(",");
        		ArrayList<String> list = new ArrayList<String>();
        		StudentExport studentExport = new StudentExport();
        		int fileType = 0;
        		String path = null;
        		if (us.length>1) {
        			fileType = 1;
        			path = wrongBookService.exportStudentPdfZip(us, subjectId, beginDate, endDate, practise);
        		} else {
        			Long userId = DataTypeUtil.toLong(userIds);
        			path = wrongBookService.productDateRangPdfA4(userId, subjectId, beginDate, endDate, practise);
        		}
        		studentExport.setDownloadLink(path + "?attname=");
        		studentExport.setFileLink(path);
        		
    			studentExport.setFileType(fileType);
    			return Response.success("成功!", studentExport);
    		} catch (Exception e) {
    			logger.error("", e);
    			return Response.error(e);
    		}
    		
    }
    

    StudentExport类:

    package com.iShift.kachaexport.entry.vo;
    
    public class StudentExport {
    	private int FileType; //1:压缩包  0:pdf
    	
    	private String FileLink;
    	
    	private String DownloadLink;
    
    	public int getFileType() {
    		return FileType;
    	}
    
    	public void setFileType(int fileType) {
    		FileType = fileType;
    	}
    
    	public String getFileLink() {
    		return FileLink;
    	}
    
    	public void setFileLink(String fileLink) {
    		FileLink = fileLink;
    	}
    
    	public String getDownloadLink() {
    		return DownloadLink;
    	}
    
    	public void setDownloadLink(String downloadLink) {
    		DownloadLink = downloadLink;
    	}
    
    }
    

    上传至7牛:

    public void storeToQiniu(byte[] bs, String relativePath) throws Exception {
    		// 构造一个带指定Zone对象的配置类
    		Configuration cfg = new Configuration(Zone.zone2());
    		// ...其他参数参考类注释
    		UploadManager uploadManager = new UploadManager(cfg);
    		// ...生成上传凭证,然后准备上传
    		// 默认不指定key的情况下,以文件内容的hash值作为文件名
    		String key = relativePath;
    		// byte[] uploadBytes = "hello qiniu cloud".getBytes("utf-8");
    		ByteArrayInputStream byteInputStream = new ByteArrayInputStream(bs);
    		Auth auth = Auth.create(Constants.ACCESS_KEY, Constants.SECRET_KEY);
    		String upToken = auth.uploadToken(Constants.QINIU_BUCKET);
    		Response response = uploadManager.put(byteInputStream, key, upToken, null, null);
    		// 解析上传成功的结果
    		DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
    		if (!relativePath.equals(putRet.key)) {
    			throw new Exception("上传文件出错!期待文件:" + relativePath + " 返回路径:" + putRet.key);
    		}
    	}
    	private static byte[] file2byte(File file) {  
            byte[] buffer = null;  
            try {  
                FileInputStream fis = new FileInputStream(file);  
                ByteArrayOutputStream bos = new ByteArrayOutputStream();  
                byte[] b = new byte[1024];  
                int n;  
                while ((n = fis.read(b)) != -1) {  
                    bos.write(b, 0, n);  
                }  
                fis.close();  
                bos.close();  
                buffer = bos.toByteArray();  
            } catch (FileNotFoundException e) {  
                e.printStackTrace();  
            } catch (IOException e)  {  
                e.printStackTrace();  
            }  
            return buffer;  
        }
    
    Ps:新手求学中,记录多文件转换压缩包过程。百度良久,自己要学的还有很多。
    展开全文
  • 最近项目需要把webpack工程化做一下优化计划把webpack打包编译的生成的文件压缩zip包上传 源码 const path = require('path'); const webpack = require('webpack'); const config = require('./webpack.config');...

    动机

    最近项目需要把webpack工程化做一下优化计划把webpack打包编译的生成的文件压缩成zip包上传

    源码

    const path = require('path');
    const webpack = require('webpack');
    const config = require('./webpack.config');
    const rm = require('rimraf');//删除文件模块
    var archiver = require('archiver');//压缩文件模块
    var archive = archiver('zip', {
      zlib: { level: 9 }
    });
    const fs = require('fs');
    function zipBall(pathname, zip) {
      archive.glob(pathname + '/**');
      archive.pipe(zip);
      //如果文件流关闭进行回调删除webpack打包生成的文件
      zip.on('close', function () {
        rm('./pathname', {}, function (err, data) {
          console.log('-----zip success----');
        })
      });
      archive.finalize();
      //输出结束
    }
    //入口函数
    run();
    function run() {
      rm(path.resolve(process.cwd(), './page.zip'), {}, function () {
        var webpackBuildPath = path.resolve(process.cwd(), './pathname ');
        var stat = fs.existsSync(webpackBuildPath);
        if (stat) {
          console.log('plan to removing %s',webpackBuildPath);
          rm(webpackBuildPath, {}, function () {
            console.log(' removed %s',webpackBuildPath);
            var compiler = webpack(config);
            compiler.run((err, stats) => {
              let messages;
              if (err) {
                if (!err.message) {
                  return reject(err);
                }
    
              }
              console.log('---------webpack build success---------')
              const zip = fs.createWriteStream('./page.zip');
              var pathname = './pathname ';
              zipBall(pathname, zip)
            })
          })
    
        } else {
          var compiler = webpack(config);
          compiler.run((err, stats) => {
            let messages;
            if (err) {
              if (!err.message) {
                return reject(err);
              }
    
            }
    
            console.log('---------webpack build success---------')
            const zip = fs.createWriteStream('./page.zip');
            var pathname = './pathname';
            zipBall(pathname, zip)
          })
        }
      })
    }
    
    展开全文
  • java后台文件下载打包成压缩包 1.service public List<Map<String,List>> downDpStyleImgList(List taskIds) throws Exception { List<Map<String,List>> resultList = new LinkedList<&...

    java后台文件下载打包成压缩包

    1.service
    public List<Map<String,List>> downDpStyleImgList(List taskIds) throws Exception {
    List<Map<String,List>> resultList = new LinkedList<>();

        List<List<BufferedImage>> listList = new LinkedList<>();
        //获取任务包下详细信息
        for (int i = 0; i < taskIds.size(); i++) {
            List<BufferedImage> list = new ArrayList<>();
            List<InputStream> inputStreamList = new ArrayList<>();
            List<String> taskNameList = new ArrayList<>();
            List<String> houseNameList = new ArrayList<>();
            Map<String,List> result = new HashMap<>(4);
    
            //获取页面勾选的每个任务包下的门牌地址数据
            Long taskId = taskIds.get(i);
            //任务包信息
            TaskPackage taskPackage = taskPackageMapper.selectById(taskId);
            //任务包名取新的任务包名称
            taskNameList.add(taskPackage.getNewTaskPackageName());
    
            //查询条件
            QueryWrapper<HouseAddress> houseAddressQueryWrapper = new QueryWrapper<>();
            houseAddressQueryWrapper.eq("audit_status",HouseAddressConstants.AUDIT_STATUS_AUDIT);
            houseAddressQueryWrapper.eq("recommend_addr",HouseAddressConstants.RESERVE_YEW);
            houseAddressQueryWrapper.eq("task_id",taskId);
            houseAddressQueryWrapper.in("status",HouseAddressConstants.STATUS_PRODUCER,HouseAddressConstants.STATUS_BEFOREPRODUCER);
            houseAddressQueryWrapper.orderByAsc("num_code");
            houseAddressQueryWrapper.in("task_status",HouseAddressConstants.TASK_STATUS_NOPRODUCER,HouseAddressConstants.TASK_STATUS_PRODUCER,HouseAddressConstants.TASK_STATUS_PRODUCER_FINISH);
            houseAddressQueryWrapper.ne("operation_type",HouseAddressConstants.OPERATION_TYPE_DELETE);
            List<HouseAddress> houseAddressList = this.list(houseAddressQueryWrapper);
    
    
            if(CollectionUtils.isNotEmpty(houseAddressList)){
                for (HouseAddress house:houseAddressList) {
                    Map<String,String> map = new HashMap<>(4);
                    String stdId = house.getStdId();
                    DpStyleDto dpStyleDto = getDpStyle(stdId);
                    if(dpStyleDto != null){
                        String type = dpStyleDto.getDoorClass();
                        //查询条件
                        QueryWrapper<DpStyleConfig> dpStyleConfigQueryWrapper = new QueryWrapper<>();
                        dpStyleConfigQueryWrapper.eq("name", type);
                        DpStyleConfig dpStyleConfig = dpStyleConfigMapper.selectOne(dpStyleConfigQueryWrapper);
                        getStyleMap(house, map, dpStyleDto, type, dpStyleConfig);
    
                        BufferedImage bufferedImage= HtmlImageGeneratorUtil.graphicsHtmlGeneration(map,type,house.getDoorNum());
    
                        list.add(bufferedImage);
                        if(bufferedImage != null){
                            //BufferedImage 转 InputStream
                            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                            ImageOutputStream imageOutput = ImageIO.createImageOutputStream(byteArrayOutputStream);
                            ImageIO.write(bufferedImage, "png", imageOutput);
                            InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
                            long length = imageOutput.length();
                            inputStreamList.add(inputStream);
                        }
                        houseNameList.add(house.getDoorNum());
                    }
                }
            }
            result.put("taskName",taskNameList);
            result.put("InputStream",inputStreamList);
            result.put("houseNameList",houseNameList);
            resultList.add(result);
        }
        return resultList;
    }
    

    2.controller
    @RequestMapping(value = “/downDpStyleImgListNew”,method = RequestMethod.POST )
    public void downDpStyleImgListNew(@RequestParam(value = “list”)List list ,HttpServletRequest request, HttpServletResponse response) throws Exception {

        List<Map<String, List>> lists = houseAddressService.downDpStyleImgList(list);
        String outputFileName = "门牌样式" + System.currentTimeMillis()+ ".zip";
        //名称处理即可解决文件名下载后乱码的问题
        String userAgent = request.getHeader("User-Agent");
        // 针对IE或者以IE为内核的浏览器:
        if (userAgent.contains(CommonConstants.MSIE) || userAgent.contains(CommonConstants.TRIDENT)) {
            outputFileName = java.net.URLEncoder.encode(outputFileName, "UTF-8");
        } else {
            // 非IE浏览器的处理:
            outputFileName = new String(outputFileName.getBytes("UTF-8"), "ISO-8859-1");
        }
        // 设置response参数
        response.setContentType("content-type:octet-stream;charset=UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String((outputFileName).getBytes(), "UTF-8"));
        ServletOutputStream out = response.getOutputStream();
        if(CollectionUtils.isNotEmpty(lists)){
            ZipOutputStream  zous = new ZipOutputStream (out);
            try {
                for (Map<String, List> map:lists) {
                    List<String> taskNameList = map.get("taskName");
                    List<String> houseNameList = map.get("houseNameList");
                    List<InputStream> inputStreamList = map.get("InputStream");
                    if(CollectionUtils.isNotEmpty(inputStreamList)){
                        for (int i = 0; i < inputStreamList.size(); i++) {
    
                            ByteArrayOutputStream baos = new ByteArrayOutputStream();
                            byte[] buffer = new byte[1024];
                            int len;
                            while ((len = inputStreamList.get(i).read(buffer)) != -1) {
                                baos.write(buffer, 0, len);
                            }
                            if (baos != null) {
                                baos.flush();
                            }
                            byte[] bytes = baos.toByteArray();
                            //设置文件名
                            ZipEntry entry = new ZipEntry(taskNameList.get(0)+ File.separator+ houseNameList.get(i)+i+ System.currentTimeMillis()+ ".png");
                            zous.putNextEntry(entry);
                            zous.write(bytes);
                            zous.closeEntry();
                            if (baos != null) {
                                baos.close();
                            }
                        }
                    }
                }
            }catch (IOException e) {
                logger.error(e.getMessage(),e);
            }finally{
                if (zous != null) {
                    zous.close();
                }
            }
        }
    
    }
    
    展开全文
  • 批量下载文件打包成zip压缩包

    千次阅读 2017-11-10 14:56:41
    批量下载文件,用程序打zip压缩包在下载 前台传来要下载的文件url数组 @RequestMapping(value = "/download",method = RequestMethod.POST) public void download(HttpServletResponse response,String [] ...

    批量下载文件,用程序打成zip压缩包在下载

    前台传来要下载的url数组

    @RequestMapping(value = "/download",method = RequestMethod.POST)  
    public void download(HttpServletResponse response,String [] filePathList) throws IOException{  
    	// 通过response对象获取OutputStream流  
    	OutputStream os = response.getOutputStream();  
    	//获取zip的输出流  
            ZipOutputStream zos = new ZipOutputStream(os);  
    	//定义输入流  
            BufferedInputStream bis = null;  
      
    	try {  
    		//循环url数组  
    		for (String path : filePathList) {  
      			//通过url地址获取连接  
    			URL url = new URL(path);  
    			HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
      
    			//设置超时间为3秒     
    			conn.setConnectTimeout(3*1000);    
      
    			//防止屏蔽程序抓取而返回403错误    
    			conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");    
    			conn.setRequestMethod("GET");  
    			conn.connect();  
      
    			//通过连接得到输入流    
    			InputStream inputStream = conn.getInputStream();   
      
    			//设置压缩后的zip文件名  
    			String sourceFilePath = "zip.zip";  
      
    			//设置content-disposition响应头控制浏览器弹出保存框,若没有此句则浏览器会直接打开并显示文件。  
    			//中文名要经过URLEncoder.encode编码,否则虽然客户端能下载但显示的名字是乱码  
      
           			response.setHeader("content-disposition", "attachment;filename="   
    			+ URLEncoder.encode(sourceFilePath, "UTF-8"));  
      
    			byte[] buf = new byte[8192];  
            		int len = 0;  
      
            		//创建ZIP实体,并添加进压缩包    
            		ZipEntry zipEntry = new ZipEntry(fileName);    
            		zos.putNextEntry(zipEntry);    
            		bis = new BufferedInputStream(inputStream, 1024*10);    
           			while ((len = bis.read(buf)) > 0) {  
            		//使用OutputStream将缓冲区的数据输出到客户端浏览器  
            		zos.write(buf, 0, len);  
            		}    
    		}  
    	} catch (Exception e) {  
    		e.printStackTrace();  
    	}finally{  
    		if(null != zos) zos.close();  
    		if(null != bis) bis.close();  
    	}  
    }            
    
    


    展开全文
  • MVC实现实现文件打包成压缩包1、使用压缩类库SharpZipLib SharpZipLib 是一款比较经典实用C#压缩类库SharpZipLib 库特点:功能丰富、稳...
  • JAVA将多个文件打包成ZIP压缩包输出

    千次阅读 2019-07-01 11:36:21
    工具类一(将多个远端文件读取并压缩) import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import ...
  • Python 将多层文件夹里面的文件打包为zip压缩包 将file文件夹里面的key文件夹里面的所有内容打包为zip压缩包。 文件夹结构如下: j@ubuntu:~/Desktop/file$ pwd /home/j/Desktop/file j@ubuntu:~/Desktop/file$ tree...
  • easyExcel导出excel文件打包成zip压缩包下载

    千次阅读 热门讨论 2020-04-22 14:59:15
    // 读入需要下载的文件的内容,打包到zip文件 while ((len = fis.read(buffer)) > 0) { out.write(buffer, 0, len); } out.closeEntry(); fis.close(); } out.close(); //下载zip文件 this.downFile(response, ...
  • java打包文件生成zip压缩包

    千次阅读 2019-04-22 13:31:15
    java打包文件生成zip压缩包
  • 项目开发过程中关于一个订单所有附件的导出引发的一个问题,刚开始的时候在后端打包并压缩,返回stream流给前端,前端通过a标签下载流,但是在文件比较大的时候会出现问题,后端压缩的时候采用的是archiver,前端...
  • 前端批量下载文件、图片、打包成压缩包,JZip和file-saver
  • 读取FTP文件,并打包成压缩包下载

    千次阅读 2018-08-23 15:52:17
    import java.io.*; import java.net.SocketException; import java.net.URLEncoder; import java.util.List;... logger.error("文件打包下载有误: " + e.getLocalizedMessage()); e.printStackTrace(); } } }
  • 我使用的class_phpzip.php 插件打包zip,对class_phpzip.php 文件,增加了一个文件名数组,直接上代码,从代码里面看比较方便 <?php # # PHPZip v1.2 by Sext (sext@neud.net) 2002-11-18 # (Changed: 2003-03-...
  • packFileToZip可以将指定目录(tempFileDir)下的所有文件打包成指定zipName的压缩包,保存在tempZipDir中,然后再通过response获取流响应给前端,其中有使用到IOutil工具类,用于将文件通过流写入磁盘,请自行修改...
  • VC6 插件 ProjectZip,在工具栏上生成图标,快速打包项目文件.
  • 用Python将文件进行压缩,可以使用 zipfile库,提供了非常丰富的API。 zipfile本身是上下文管理器, 可以使用with。以下为自己简单写的Demo。 import os import zipfile def file2zip(zip_file_name: str, file_...
  • js打包,创建压缩包

    2019-08-13 11:26:07
    创建压缩顺序: 先引入zlib,zlib是一个压缩包的内置快const zlib = require(‘zlib’) 创建一个空压缩包const ...创建可读的流const inp = fs.createReadStream ( ’ 要压缩文件的路径 ’ ) 创建可写的流const ou...
  • 前言:最近项目有个需求,需要生成多个 excel并打包成 zip下载;由于需要生成的 excel头字段过多,这里有96个时间段的表头,建一个实体字段太多了,还好 easyExcel支持 List生成表头。 1、导入 Maven坐标,这里用到...
  • 上一篇文章讲解了如何生成excel文件,name这一章我们来谈谈如何将多个excel文件打包成压缩包的形式 首先看一下主函数: public static void main(String[] args) throws IOException { try { File file1 = ...
  • 一、文件打包为zip public void zip(List<File> fileList,String zipFileName) { FileInputStream fileInputStream = null; FileOutputStream fileOutputStream = null; ZipOutputStream ...
  • Android Studio的工程打成压缩包后都会比较大,这是因为里面包含了一堆编译文件。动辄几百兆的工程伤不起啊!@淡定的程序猿在文章里推荐使用打包工具的排除功能,如果使用Windows的朋友可以参考...
  • FTP下载多个文件打包成一个压缩包

    千次阅读 2018-10-12 13:17:39
     //每个人问资料打包成一个文件夹,所有人的文件夹打包成一个压缩包  String workids ="";  String xm ="";  //打包  byte[] buf = new byte[2048];  File zipFile = new File("d:\\EntryMaterialsPl"); ...
  • 将E盘zip文件夹下面的内容打成压缩包保存到E盘目录下 代码实现:ZipUtil.java import java.io.FileOutputStream; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.ArrayUtils; import ...
  • 根据如上随笔记录,多个文件下载成压缩包压缩包下载成功。但是解压时提示报错: 利用程序打包并下载的zip压缩包:用“306压缩软件”能打开;用“winrar软件”打不开,提示报错内容损失 具体原因如下图,低级错误...
  • tar czvf test.tar.gz * 压缩当前文件夹下非[隐藏文件]的文件 tar czvf test.tar.gz .[!.]* 压缩当前文件夹下[隐藏文件]排除两个[隐藏文件]夹"."和“..” 转载于:https://www.cnblogs.com/ysk123...
  • // 解决不同浏览器压缩包名字含有中文时乱码的问题 String downloadName = System . currentTimeMillis ( ) + ".zip" ; String agent = request . getHeader ( "USER-AGENT" ) ; try { if ( ...
  • (Java控制台程序版)递归打包整个父文件夹下的文件和子文件夹压缩文件(*.ZIP)以及打包时常见的文件乱码和文件名乱码以及丢失文件文件损坏问题解决办法
  • 将手机微信的图片打包成压缩包

    千次阅读 2020-04-26 17:29:14
    创建文件夹 输入文件名 查看图片 多选图片
  • webpack将文件成压缩包

    千次阅读 2019-06-19 10:43:07
    英文好的直接看文档 ...引包 npm install filemanager-webpack-plugin --save-dev 修改配置文件 ./build/webpack.dev.conf.js // 引包 const FileManagerPlugin = require('file...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 56,427
精华内容 22,570
关键字:

怎么打包文件成压缩包