1. 程式人生 > 其它 >JAVA-批量下載zip

JAVA-批量下載zip

案例一

    @ApiOperation(value = "根據id 批量下載檔案", notes = "根據id 批量下載檔案")
    @RequestMapping(value = "/downloadFiles/{id}", method = RequestMethod.GET)
    @ApiImplicitParam(name = "sheetId", value = "工單ID", required = true, dataType = "String", paramType = "path")
    public void downloadFiles(HttpServletRequest request, HttpServletResponse response, @PathVariable String id) throws Exception {
        List<OssMediaFile> list = null;
        try {
            EntityWrapper<OssMediaFile> wrapper = new EntityWrapper<>();
            wrapper.eq("id", id);
            wrapper.eq("is_delete", 0);
            list = this.baseService.selectList(wrapper);
            response.setContentType("text/html;charset=UTF-8");
            request.setCharacterEncoding("UTF-8");
            String header = request.getHeader("User-Agent").toUpperCase();
            String fileName = "附件" + String.valueOf(System.currentTimeMillis()) + ".zip";
            if (!header.contains("MSIE") && !header.contains("TRIDENT") && !header.contains("EDGE")) {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } else {
                fileName = URLEncoder.encode(fileName, "utf-8");
                fileName = fileName.replace("+", "%20");
            }
            response.setContentType("multipart/form-data");
            response.setHeader("Content-disposition", "attachment; filename=" + fileName);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        try(ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream())) {
            for (int i = 0; i < list.size(); i++) {
                OssMediaFile mediaFile = list.get(i);
                logger.info("ossMediaFile引數:{}", JSONObject.toJSONString(mediaFile));
                InputStream is = null;
                try {
                    zipOut.putNextEntry(new ZipEntry(mediaFile.getFileName()));
                    String urlName = mediaFile.getFileUrl();
                    URL url = new URL(urlName);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    // 設定是否向HttpURLConnection輸出
                    conn.setDoOutput(false);
                    // 設定是否從httpUrlConnection讀入
                    conn.setDoInput(true);
                    /** 設定連線方式:GET */
                    conn.setRequestMethod("GET");
                    /** 設定連線主機伺服器超時時間:5000毫秒 */
                    conn.setConnectTimeout(5000);
                    /** 傳送GET方式請求,使用connet方法建立和遠端資源之間的實際連線即可 */
                    conn.connect();
                    int status = conn.getResponseCode();
                    logger.info("---status:" + status);
                    if(status!= HttpURLConnection.HTTP_OK){
                        is = conn.getErrorStream();
                    }else{
                        is = conn.getInputStream();
                    }
                    if (null == is) {
                        continue;
                    }
                    int temp = 0;
                    while ((temp = is.read()) != -1) {
                        zipOut.write(temp);
                    }
                    is.close();
                    /** 關閉遠端連線 */
                    conn.disconnect();
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                }
            }
            zipOut.closeEntry();
            logger.info("一鍵下載結束");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new RuntimeException("附件下載失敗");
        }
    }