Java HttpServletResponse 下载文件功能实现 - 使用 ZipOutputStream 压缩文件
/**
-
下载文件
-
@param request HttpServletRequest对象
-
@param response HttpServletResponse对象
-
@param id 文件id
-
@param dept 部门 */ public void downloadFile(HttpServletRequest request, HttpServletResponse response, Long id,String dept) { ZipOutputStream zos = null; OutputStream out = null; //获取新文件列表 String progressName = jadNewReportFileService.getNewFileList(getUser(), id,getServletContext(),dept); //获取真实路径 String realPath = getServletContext().getRealPath(PortionPath.DELETED_FILE +progressName);
//以下为注释掉的代码,未使用 // JadAgrunitauditEntity audit = jadCommonReportService.getAuditById(id); // if(audit.getLevel()==PlaceLevel.TOWN.ordinal()){ // String imagePath = getServletContext().getRealPath('resources'); // imagePath+='/images/shuiying.png'; // List
vils = jadCommonReportService.getVillageReportByAuditId(id); // List nats = jadCommonReportService.getNatReportByAuditId(id); // List devices = jadCommonReportService.getStDeviceByAuditId(id); // Map<Long,JadNvfillformEntity> map_nats = new HashMap<>(); // Map<Long,JadVillagereportEntity> map_vils = new HashMap<>(); // Map<Long,List > map_devices = new HashMap<>(); // Map<File,JadFillformEntity> map_files = new HashMap<>(); // for(JadNvfillformEntity ns:nats){ // map_nats.put(ns.getId(),ns); // } // for(JadVillagereportEntity vs:vils){ // map_vils.put(vs.getId(),vs); // } // for(JadNvSTfillformEntity device:devices){ // List fields = map_devices.get(device.getNatReport().getId()); // if(fields==null){ // fields=new ArrayList<>(); // } // fields.add(device.getField()); // map_devices.put(device.getNatReport().getId(),fields); // } // try { // createPdfFile(new File(realPath),map_files,map_vils,map_nats); // } catch (Exception e) { // e.printStackTrace(); // } // Long startTime=System.currentTimeMillis(); // try { // CountDownLatch latch=new CountDownLatch(map_files.size()); // for(Map.Entry<File, JadFillformEntity> entry : map_files.entrySet()){ // File key = entry.getKey(); // JadFillformEntity value = entry.getValue(); // PdfThread pdfThread = new PdfThread(applicationContext,imagePath,key,value,map_devices, latch); // pdfThread.start(); // } // latch.await(); // } catch (Exception e) { // e.printStackTrace(); // } // Long endTime=System.currentTimeMillis(); // System.out.println('over 耗时:'+(endTime-startTime)); // } try { response.setContentType('application/x-zip-compressed'); //设置文件名编码 String fileName = new String((progressName+'.zip').getBytes('utf-8'),'iso-8859-1'); response.setHeader('Content-disposition', 'attachment;filename=' +fileName); out = response.getOutputStream(); zos = new ZipOutputStream(out); //压缩文件夹 ZipUtils.toZip(realPath, out, true); } catch (Exception e) { e.printStackTrace(); }finally { if (out != null) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } }
原文地址: https://www.cveoy.top/t/topic/n9wE 著作权归作者所有。请勿转载和采集!