Java以壓縮包方式下載文件


從雲服務器上下載文件,以壓縮包方式下載

  • 以下載多個文件為例,需要導入zip4j的jar包,版本不要太高
public void downloadZip(List<fielEntiry> list, HttpServletRequest request, HttpServletResponse response) {
                String zipFileName = "";
                File[] tempList = null;
		//因為我這邊在classpath下無法獲取到新建文件夾,所以使用路徑拼接
                String path = this.getClass().getClassLoader().getResource("template/").getPath();
                path += "tempPack";
                File outFile = new File(path);
                for (fielEntiry file : list) {
                    String url = file.getUrl();//雲服務器文件鏈接
                    String fileName = assc.getFileName();

                    if (!outFile.exists()) {
                        outFile.mkdirs();
                    }
                    try {
                        download(url, path, fileName);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                zipFileName = "/報告.zip";
                tempList = outFile.listFiles();
                createZipFile(path, zipFileName, tempList);
                for (File file : outFile.listFiles()) {
                    download(file, request, response);
                }
            } else {
                throw new BadRequestException("暫無報告附件");
            }
        }
    }

*下載文件到臨時文件夾

   public void download(String urlPath, String targetDirectory, String fileName) throws Exception {
        URL url = new URL(urlPath);
        HttpURLConnection http = (HttpURLConnection) url.openConnection();
        InputStream inputStream = http.getInputStream();
        byte[] buff = new byte[1024 * 10];
        OutputStream out = new FileOutputStream(new File(targetDirectory, fileName));
        int lenth = -1;
        while ((lenth = inputStream.read(buff)) != -1) {
            out.write(buff, 0, len);
            out.flush();
        }
        // 關閉資源
        out.close();
        inputStream.close();
        http.disconnect();
    }

*將文件打包成zip文件

    public static ZipFile createZipFile(String templatePathZip, String fileName, File... files) {
        try { // 創建zip包,指定路徑和名稱
            final ZipFile zipFile = new ZipFile(templatePathZip + fileName);
            // 向zip包中添加文件集合
            final ArrayList<File> fileAddZip = new ArrayList<File>();
            File file1 = zipFile.getFile();
            if (file1.exists()) {
                file1.delete();
            }
		// 向zip包中添加文件
            for (File file : files) {
                fileAddZip.add(file);
            }
		// 設置zip包的一些參數集合
            final ZipParameters parameters = new ZipParameters();
		// 是否設置密碼(若passwordZip為空,則為false)
            /*if (null != passwordZip && !passwordZip.equals("")) {
                parameters.setEncryptFiles(true);
                // 壓縮包密碼
                parameters.setPassword(passwordZip);
            } else { }*/
            parameters.setEncryptFiles(false);

		// 壓縮方式(默認值)
            parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
		// 普通級別(參數很多)
            // parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
		// 加密級別
            // parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_STANDARD);
		// 創建壓縮包完成
            zipFile.createZipFile(fileAddZip, parameters);
		//壓縮完成后刪除文件
            for (File file : files) {
                file.delete();
            }
            return zipFile;
        } catch (final Exception e) {
            e.printStackTrace();
            return null;
        }
    }

*下載生成的word文件並刪除臨時文件

    private void download(File file, HttpServletRequest request, HttpServletResponse response) {

        ServletOutputStream out = null;
        FileInputStream inputStream = null;
        try {
            String filename = file.getName();
            String userAgent = request.getHeader("User-Agent");
            // 針對IE或者以IE為內核的瀏覽器:
            if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
                filename = java.net.URLEncoder.encode(filename, "UTF-8");
            } else {
                // 非IE瀏覽器的處理:
                // filename = URLEncoder.encode(filename, "UTF-8");
                filename = new String(filename.getBytes("UTF-8"), "ISO-8859-1");
            }
            response.setHeader("Content-disposition",
                    String.format("attachment; filename=\"%s\"", filename));
            response.setContentType("application/download");
            response.setCharacterEncoding("UTF-8");
            out = response.getOutputStream();
            inputStream = new FileInputStream(file);
            byte[] buffer = new byte[1024 * 10];
            int lenth = -1;
            // 通過循環將讀入的Word文件的內容輸出到瀏覽器中
            while ((lenth = inputStream.read(buffer)) != -1) {
                out.write(buffer, 0, bytesToRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != out) out.close();
                if (null != inputStream) inputStream.close();
                file.delete();
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }

注:部分代碼是在網上查找的資料,然后根據自己需要寫的


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM