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

来源:互联网 发布:打码识别软件 编辑:程序博客网 时间:2024/04/29 02:09

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

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 {@Autowiredprivate 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;}}


原创粉丝点击