SpringMVC檔案打包下載

來源:互聯網
上載者:User

最近做了一個ABTest的應用,使用者希望對ABTest的結果能夠打包批量進行下載,這個時候就需要先對下載的多個檔案進行壓縮打包,再進行下載。

@RequestMapping("/download")public Object export(HttpServletRequest request, HttpServletResponse response, @RequestParam String batchId,) throws IOException {       List<UserInfo> list = userDao.getUsers(batchId);       String tmpdir = System.getProperty("java.io.tmpdir");        if(StringUtils.isEmpty(tmpdir)){            logger.info("tmpdir is empty, use ServletContextPath");            tmpdir = request.getServletContext().getContextPath();        }        logger.info("export tmpdir:{}", tmpdir);        File tempDir = new File(tmpdir+File.separator+"download");        if(!tempDir.exists()){            boolean success = tempDir.mkdirs();            logger.info("create tempDir:{}, success:{}", tempDir.getAbsolutePath(), success);        }       File zipFile = new File(tempDir, String.format("%s.zip", batchId)); //壓縮後的檔案        OutputStream out = null;        InputStream in = null;        try {            convert(list, zipFile);            response.setContentType("application/octet-stream; charset=utf-8");            response.setHeader("Content-Disposition", "attachment; filename=" + zipFile.getName());            out = response.getOutputStream();            in = new FileInputStream(zipFile);            IoUtils.copy(in, out);        } catch (IOException e) {            logger.error("export file error", e);        }finally {            IoUtils.closeQuietly(out);            IoUtils.closeQuietly(in);        }}
private void convert(List<UserInfo> list, File zipFile){    ZipOutputStream zipOut = null;       try {           zipOut = new ZipOutputStream(new FileOutputStream(zipFile));           for (UserInfo info : list){               addZipEntry(zipOut, info.getId()+".txt", info.getName()+"\t"+info.getPassword());           }           zipOut.flush();       } catch (Exception e) {           logger.error("export data failed, type:"+type+", batchId:"+batchId, e);           throw new RuntimeException("export data failed, type:"+type+", batchId:"+batchId, e);       }finally {           IoUtils.closeQuietly(zipOut);       }}
private void addZipEntry(ZipOutputStream zipOut, String name, String data) throws IOException {    zipOut.putNextEntry(new ZipEntry(name));    zipOut.setComment("");    if(StringUtils.isEmpty(data)){        data = " ";    }    zipOut.write(data.getBytes("UTF-8"));}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.