Java多文件打包为一个压缩包下载

前段时间有一个需求,是将符合给定条件的车辆的铭牌照片打包成一个压缩包供用户下载,照片名字以车架号命名,趁假期整理下实现方法。

 

package com.dz.baoguan.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.dz.baoguan.vo.BrandEnum;
import com.dz.dao.MyBatisDao;

/**
 * 
 * @description 铭牌照片
 * @date 2017年8月24日
 *
 */
@Controller
@RequestMapping(value = "/baoguan/Nameplate")
public class NameplateImagesController {
	
	@Autowired
	private MyBatisDao dao;
	
	private static final String EMPTY = "";
	private static final String ZIP = ".zip";
	
	private static final Logger LOGGER = Logger.getLogger(NameplateImagesController.class);

	/**
	 * 
	 * @description 铭牌照片导出
	 * @param 
	 * @return voi
	 * @date 2017年8月24日
	 */
	@RequestMapping(value = "/exportImages")
	public void exportExcel(HttpServletRequest req, HttpServletResponse resp) {
		
		try {
			req.setCharacterEncoding("UTF-8");
			
			//拿到项目根路径
			@SuppressWarnings("deprecation")
			String basePath = req.getRealPath("/");
			LOGGER.debug("【拿到的根路径】 " + basePath);
			
			List> result = getDatas(req);
			
			//zip文件导出名称,路径等设置
			String voyage_no = EMPTY;
			try {
				voyage_no = result.get(0).get("voyage_no").toString();
			} catch (Exception e) {
				LOGGER.error("【拿到的请求参数】 " + req.getParameter("brand"));
				voyage_no = req.getParameter("brand").toString().trim();
			}
			
			String zipName = voyage_no + new Date().getTime() + ZIP;
			zipName = URLEncoder.encode(zipName, "UTF-8");
			
			resp.setContentType("application/octet-stream; charset=UTF-8");// 指明response的返回对象是文件流
			resp.setHeader("Content-Disposition", "attachment;filename=" + zipName);// 设置在下载框默认显示的文件名
			
			ZipOutputStream zos = new ZipOutputStream(resp.getOutputStream());
			
			//从查询结果中拿到图片路径
			for(Map map : result) {
				if(map.get("img_path") == null || StringUtils.isBlank(map.get("img_path").toString())) {
					continue;
				}
				String imgPath = basePath + map.get("img_path").toString().trim();
				//根据图片路径拿到图片流对象
				File image = new File(imgPath);
				if(!image.exists()) {
					LOGGER.error(imgPath + " ### 该路径无有效图片。");
					continue;//如果某张图片不存在,跳过该图片
				}
				FileInputStream fis = new FileInputStream(image);
				//车架号作为图片名称
				zos.putNextEntry(new ZipEntry(map.get("frame_no").toString() + ".jpg"));
				byte[] buffer = new byte[1024];
                int r = 0;
                while ((r = fis.read(buffer)) != -1) {
                    zos.write(buffer, 0, r);
                }
                fis.close();
			}
			zos.flush();
            zos.close();
            
		} catch (UnsupportedEncodingException e) {
			LOGGER.error(e.getMessage());
		} catch (FileNotFoundException e) {
			LOGGER.error(e.getMessage());
		} catch (IOException e) {
			LOGGER.error(e.getMessage());
		} catch (Exception e) {
			LOGGER.error(e.getMessage());
		}                      
	}
	
	private List> getDatas(HttpServletRequest req) {
		//从HttpServletRequest拿到请求参数,查询数据库
		int checkStatus = 2;
		int checkResult = 2;
		try {
			checkStatus = Integer.valueOf(req.getParameter("checkStatus").toString().trim());
		} catch (Exception e) {
			checkStatus = 2;//默认查询全部
		}
		try {
			checkResult = Integer.valueOf(req.getParameter("checkResult").toString().trim());
		} catch (Exception e) {
			checkResult = 2;//默认查询全部
		}
		//0:只查询有照片的,1:只查询无照片的,2:查所有
		int onlyHasImage;
		try {
			onlyHasImage = req.getParameter("hasImage") == null ? 0 : Integer.valueOf(req.getParameter("hasImage").toString().trim());
		} catch (NumberFormatException e1) {
			onlyHasImage = 2;
		}

		String voyageNo = req.getParameter("voyageNo") == null ? EMPTY : req.getParameter("voyageNo").toString().trim();
		String frameNo = req.getParameter("frameNo") == null ? EMPTY : req.getParameter("frameNo").toString().trim();
		String brand = req.getParameter("brand") == null ? EMPTY : req.getParameter("brand").toString().trim();
		String checkUser = req.getParameter("checkUser") == null ? EMPTY : req.getParameter("checkUser").toString().trim();
		String bTime = req.getParameter("bTime") == null ? EMPTY : req.getParameter("bTime").toString().trim();
		String eTime = req.getParameter("eTime") == null ? EMPTY : req.getParameter("eTime").toString().trim();
		
		int fromNo;
		try {
			fromNo = req.getParameter("fromNo") == null ? 0 : Integer.valueOf(req.getParameter("fromNo").toString().trim());
		} catch (NumberFormatException e) {
			fromNo = 0;
		}
		int toNo;
		try {
			toNo = req.getParameter("toNo") == null ? Integer.MAX_VALUE : Integer.valueOf(req.getParameter("toNo").toString().trim());
		} catch (NumberFormatException e) {
			toNo = Integer.MAX_VALUE;
		}
		String brandCN = BrandEnum.getBrandEnumByShortName(brand).getChineseName();
		
		Map params = new HashMap();
		params.put("has_checked", checkStatus);
		params.put("is_correct", checkResult);
		params.put("voyage_no", voyageNo);
		params.put("frame_no", frameNo);
		params.put("brand", brandCN);
		params.put("from_no", fromNo);
		params.put("to_no", toNo);
		params.put("bTime", bTime == EMPTY ? null : bTime + " 00:00:00");
		params.put("eTime", eTime == EMPTY ? null : eTime + " 23:59:59");
		params.put("update_user", checkUser);
		params.put("only_has_image", onlyHasImage);
		List> result = dao.getList("com.dz.baoguan.mapper.NameplateMapper.getActiveDatas", params);
		//数据查询结束
		
		return result;
	}
}
> result = getDatas(req);
			
			//zip文件导出名称,路径等设置
			String voyage_no = EMPTY;
			try {
				voyage_no = result.get(0).get("voyage_no").toString();
			} catch (Exception e) {
				LOGGER.error("【拿到的请求参数】 " + req.getParameter("brand"));
				voyage_no = req.getParameter("brand").toString().trim();
			}
			
			String zipName = voyage_no + new Date().getTime() + ZIP;
			zipName = URLEncoder.encode(zipName, "UTF-8");
			
			resp.setContentType("application/octet-stream; charset=UTF-8");// 指明response的返回对象是文件流
			resp.setHeader("Content-Disposition", "attachment;filename=" + zipName);// 设置在下载框默认显示的文件名
			
			ZipOutputStream zos = new ZipOutputStream(resp.getOutputStream());
			
			//从查询结果中拿到图片路径
			for(Map map : result) {
				if(map.get("img_path") == null || StringUtils.isBlank(map.get("img_path").toString())) {
					continue;
				}
				String imgPath = basePath + map.get("img_path").toString().trim();
				//根据图片路径拿到图片流对象
				File image = new File(imgPath);
				if(!image.exists()) {
					LOGGER.error(imgPath + " ### 该路径无有效图片。");
					continue;//如果某张图片不存在,跳过该图片
				}
				FileInputStream fis = new FileInputStream(image);
				//车架号作为图片名称
				zos.putNextEntry(new ZipEntry(map.get("frame_no").toString() + ".jpg"));
				byte[] buffer = new byte[1024];
                int r = 0;
                while ((r = fis.read(buffer)) != -1) {
                    zos.write(buffer, 0, r);
                }
                fis.close();
			}
			zos.flush();
            zos.close();
            
		} catch (UnsupportedEncodingException e) {
			LOGGER.error(e.getMessage());
		} catch (FileNotFoundException e) {
			LOGGER.error(e.getMessage());
		} catch (IOException e) {
			LOGGER.error(e.getMessage());
		} catch (Exception e) {
			LOGGER.error(e.getMessage());
		}                      
	}
	
	private List> getDatas(HttpServletRequest req) {
		//从HttpServletRequest拿到请求参数,查询数据库
		int checkStatus = 2;
		int checkResult = 2;
		try {
			checkStatus = Integer.valueOf(req.getParameter("checkStatus").toString().trim());
		} catch (Exception e) {
			checkStatus = 2;//默认查询全部
		}
		try {
			checkResult = Integer.valueOf(req.getParameter("checkResult").toString().trim());
		} catch (Exception e) {
			checkResult = 2;//默认查询全部
		}
		//0:只查询有照片的,1:只查询无照片的,2:查所有
		int onlyHasImage;
		try {
			onlyHasImage = req.getParameter("hasImage") == null ? 0 : Integer.valueOf(req.getParameter("hasImage").toString().trim());
		} catch (NumberFormatException e1) {
			onlyHasImage = 2;
		}

		String voyageNo = req.getParameter("voyageNo") == null ? EMPTY : req.getParameter("voyageNo").toString().trim();
		String frameNo = req.getParameter("frameNo") == null ? EMPTY : req.getParameter("frameNo").toString().trim();
		String brand = req.getParameter("brand") == null ? EMPTY : req.getParameter("brand").toString().trim();
		String checkUser = req.getParameter("checkUser") == null ? EMPTY : req.getParameter("checkUser").toString().trim();
		String bTime = req.getParameter("bTime") == null ? EMPTY : req.getParameter("bTime").toString().trim();
		String eTime = req.getParameter("eTime") == null ? EMPTY : req.getParameter("eTime").toString().trim();
		
		int fromNo;
		try {
			fromNo = req.getParameter("fromNo") == null ? 0 : Integer.valueOf(req.getParameter("fromNo").toString().trim());
		} catch (NumberFormatException e) {
			fromNo = 0;
		}
		int toNo;
		try {
			toNo = req.getParameter("toNo") == null ? Integer.MAX_VALUE : Integer.valueOf(req.getParameter("toNo").toString().trim());
		} catch (NumberFormatException e) {
			toNo = Integer.MAX_VALUE;
		}
		String brandCN = BrandEnum.getBrandEnumByShortName(brand).getChineseName();
		
		Map params = new HashMap();
		params.put("has_checked", checkStatus);
		params.put("is_correct", checkResult);
		params.put("voyage_no", voyageNo);
		params.put("frame_no", frameNo);
		params.put("brand", brandCN);
		params.put("from_no", fromNo);
		params.put("to_no", toNo);
		params.put("bTime", bTime == EMPTY ? null : bTime + " 00:00:00");
		params.put("eTime", eTime == EMPTY ? null : eTime + " 23:59:59");
		params.put("update_user", checkUser);
		params.put("only_has_image", onlyHasImage);
		List> result = dao.getList("com.dz.baoguan.mapper.NameplateMapper.getActiveDatas", params);
		//数据查询结束
		
		return result;
	}
}

 

 

 

 

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值