图片打包zip

 pom文件配置

<dependency>  
        	<groupId>org.apache.commons</groupId>  
        	<artifactId>commons-compress</artifactId>  
        	<version>1.5</version>  
</dependency>

 业务类:根据实际请况修改

@RequestMapping("/imgload")
public void imgload(final HttpServletRequest request,final HttpServletResponse response,@FormModel ZlBWangshengBusiness zlBWangshengBusiness,@FormModel Processor processor){
		try{
			synchronized(this){
				final String encoding = System.getProperty("file.encoding");      
				//定义根路径
				String rootPath = request.getRealPath("/");
				log.info("根路径:"+rootPath);
				//创建文件
				String parentpath="/B_wangsheng_img";//"D:\\B_wangsheng_img";
				//压缩包的名
				String name = "B_wangsheng";
				String fileName = name+new Date().getTime();
				String zipFileName = fileName + ".zip";
				
				//首先删除可能存在的临时文件夹
				File temimageFile = new File(parentpath);
				if (temimageFile.exists()) {
					boolean debl=ExportPicture.deleteDir(temimageFile);
					while(!debl){
						debl=ExportPicture.deleteDir(temimageFile);
					}
				}
				Pagination<ZlBWangshengDetail>  imgpagelist = 
						zlBWangshengBusinessForManagerService.queryZlBWangshengDetailList(zlBWangshengBusiness,1,-1);
				List<ZlBWangshengDetail> imglist = imgpagelist.getRecords();
				
				for(int i=0;i<imglist.size();i++){
					ZlBWangshengDetail imgentity = imglist.get(i);
					String typecodename=imgentity.getModelname();//文件夾名
					String imgurl=imgentity.getPicture();//图片网络路径
					String realfilename=imgurl.split("/")[imgurl.split("/").length-1];//图片名
					String applyfilename=imgentity.getTradername()+imgentity.getApplytime();
					String temp_path=parentpath+File.separator+fileName+File.separator+applyfilename+File.separator+typecodename;
					temp_path=new String(temp_path.getBytes("UTF-8"), encoding);//解决中文乱码问题
					log.info("创建的临时文件夹--"+temp_path);
					File file = new File(temp_path);
					//判断文件是否存在,如果不存在,则创建此文件夹
					if(!file.exists()){file.mkdirs();}
					//调用工具类获取图片
					log.info("将要获取的网络图片路径--"+imgurl);
					byte[] data = ImageByteUtil.getImageFromNetByUrl(imgurl);
					if(data != null){
						//new一个文件对象用来保存图片,默认保存当前工程根目录  
						log.info("文件对象用来保存图片--"+temp_path+File.separator+realfilename);
						File imageFile = new File(temp_path+File.separator+realfilename); 
						if (!imageFile.exists()) {imageFile.createNewFile();}
						//创建输出流  
						FileOutputStream outStream = new FileOutputStream(imageFile);  
						//写入数据  
						outStream.write(data);  
						//关闭输出流  
						outStream.close();
					}
				}
					
				//获取创建好的图片文件
				log.info("建好的图片文件夹:"+parentpath);
				File imageFile1 = new File(parentpath);
				// 打成压缩包文件 
				log.info("打包的路径"+rootPath+zipFileName);
				File zipFile = new File(rootPath+zipFileName);
				//打包
				ExportPicture.zip(rootPath+zipFileName,parentpath);
				// 输出到客户端
				OutputStream out = null;
				out = response.getOutputStream();
				response.reset();
				response.setHeader("Content-Disposition", "attachment;filename=" + new                             
                 String(zipFileName.getBytes("GB2312"), "ISO-8859-1"));
				response.setContentType("application/octet-stream; charset=utf-8");
				response.setCharacterEncoding("UTF-8");
				out.write(FileUtils.readFileToByteArray(zipFile));
				out.flush();
				out.close();
				//删除文件
				if (imageFile1.exists()) {
					boolean debl=ExportPicture.deleteDir(imageFile1);
					while(!debl){
						System.gc();
						debl=ExportPicture.deleteDir(imageFile1);
					}
				}
				// 输出客户端结束后,删除压缩包
				if (zipFile.exists()) { zipFile.delete();}
				
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}

 

工具类

package com.repast.core.util;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.imageio.stream.FileImageInputStream;
import javax.imageio.stream.FileImageOutputStream;


public class ImageByteUtil {

    /**
     * 实现图片与byte数组之间的互相转换
     * @param args
     */
    public static void main(String[] args) {
        //定义路径
        String path = "C:\\Users\\周海峰\\Desktop\\9.png";//"F:\\blank.jpg";
        byte[] data = image2byte(path);
        System.out.println(data.length);
    }

    /**
     * 将图片转换为byte数组
     * @param path 图片路径
     * @return
     */
    public static byte[] image2byte(String path){
        //定义byte数组
        byte[] data = null;
        //输入流
        FileImageInputStream input = null;
        try {
          input = new FileImageInputStream(new File(path));
          ByteArrayOutputStream output = new ByteArrayOutputStream();
          byte[] buf = new byte[1024];
          int numBytesRead = 0;
          while ((numBytesRead = input.read(buf)) != -1) {
          output.write(buf, 0, numBytesRead);
          }
          data = output.toByteArray();
          output.close();
          input.close();
        }
        catch (FileNotFoundException ex1) {
          ex1.printStackTrace();
        }
        catch (IOException ex1) {
          ex1.printStackTrace();
        }
        return data;
     }

      //byte数组到图片
      public void byte2image(byte[] data,String path){
        if(data.length<3||path.equals("")) return;
        try{
        FileImageOutputStream imageOutput = new FileImageOutputStream(new File(path));
        imageOutput.write(data, 0, data.length);
        imageOutput.close();
        System.out.println("Make Picture success,Please find image in " + path);
        } catch(Exception ex) {
          System.out.println("Exception: " + ex);
          ex.printStackTrace();
        }
      }
      //byte数组到16进制字符串
      public String byte2string(byte[] data){
        if(data==null||data.length<=1) return "0x";
        if(data.length>200000) return "0x";
        StringBuffer sb = new StringBuffer();
        int buf[] = new int[data.length];
        //byte数组转化成十进制
        for(int k=0;k<data.length;k++){
          buf[k] = data[k]<0?(data[k]+256):(data[k]);
        }
        //十进制转化成十六进制
        for(int k=0;k<buf.length;k++){
          if(buf[k]<16) sb.append("0"+Integer.toHexString(buf[k]));
          else sb.append(Integer.toHexString(buf[k]));
        }
        return "0x"+sb.toString().toUpperCase();
      } 
      
      
      /**  
       * 根据地址获得数据的字节流  
       * @param strUrl 网络连接地址  
       * @return  
       */    
      public static byte[] getImageFromNetByUrl(String strUrl){    
    	  HttpURLConnection conn=null;
          try {    
              URL url = new URL(strUrl);    
               conn = (HttpURLConnection)url.openConnection();    
              conn.setRequestMethod("GET");    
              conn.setConnectTimeout(2 * 1000);  
             // conn.setReadTimeout(5000);//读数据的超时时间  
              InputStream inStream = conn.getInputStream();//通过输入流获取图片数据    
              byte[] btImg = readInputStream(inStream);//得到图片的二进制数据    
              return btImg;    
          } catch (Exception e) {    
              e.printStackTrace();    
          }finally{  
              if(conn!=null){  
                  conn.disconnect();//释放链接  
              }  
          }     
          return null;    
      }    
      /**  
       * 从输入流中获取数据  
       * @param inStream 输入流  
       * @return  
       * @throws Exception  
       */    
      public static byte[] readInputStream(InputStream inStream){    
          try {
        	  ByteArrayOutputStream outStream = new ByteArrayOutputStream();    
        	  byte[] buffer = new byte[1024];    
        	  int len = 0;    
			while( (len=inStream.read(buffer)) != -1 ){    
			      outStream.write(buffer, 0, len);    
			  }
			inStream.close(); 
			byte[] data= outStream.toByteArray();   
			outStream.flush();
			outStream.close();
			return data;
		} catch (IOException e) {
			e.printStackTrace();
		}
         return null; 
      }    

}
package com.repast.core.tool;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import org.apache.commons.compress.archivers.ArchiveException;
import org.apache.commons.compress.archivers.ArchiveOutputStream;
import org.apache.commons.compress.archivers.ArchiveStreamFactory;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
public class ExportPicture {

       
    /** 
     * 压缩  
     * @param destFile 创建的地址及名称 
     * @param zipDir 要打包的目录 
     */  
    public static void zip(String destFile, String zipDir) { 
    	System.out.println("要打包的目录:"+zipDir+"压缩包---"+destFile);
        File outFile = new File(destFile);  
        try {  
            outFile.createNewFile();  
            //创建文件  
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(  
                    new FileOutputStream(outFile));  
            ArchiveOutputStream out = new ArchiveStreamFactory()  
                    .createArchiveOutputStream(ArchiveStreamFactory.JAR,  
                            bufferedOutputStream);  
            if (zipDir.charAt(zipDir.length() - 1) != '/') {  
                zipDir += '/';  
            }  
  
            Iterator<File> files = FileUtils.iterateFiles(new File(zipDir),  
                    null, true);  
            while (files.hasNext()) {  
                File file = files.next();  
                ZipArchiveEntry zipArchiveEntry = new ZipArchiveEntry(file,  
                        file.getPath().replace(zipDir.replace("/", "\\"), ""));  
                out.putArchiveEntry(zipArchiveEntry);  
                IOUtils.copy(new FileInputStream(file), out);  
                out.closeArchiveEntry();  
            }  
            out.finish();  
            out.close();  
        } catch (IOException e) {  
            System.err.println("创建文件失败");  
        } catch (ArchiveException e) {  
            System.err.println("不支持的压缩格式");  
        }
        
    } 
   
    /**
     * 递归删除目录下的所有文件及子目录下所有文件
     * 
     * @param dir
     *            将要删除的文件目录
     * @return
     */
    public static boolean deleteDir(File dir) {
        if (!dir.exists()) return false;
        if (dir.isDirectory()) {
            String[] childrens = dir.list();
            // 递归删除目录中的子目录下
            for (String child : childrens) {
                boolean success = deleteDir(new File(dir, child));
                if (!success) return false;
            }
        }
        // 目录此时为空,可以删除
        return dir.delete();
    }
    
    public static void main(String[] args) {
    	File imageFile = new File("D:\\img");
    	deleteDir(imageFile);
	}
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值