springboot Java实现多文件的zip压缩操作 + 通过浏览器下载文件的两种方式
生活随笔
收集整理的這篇文章主要介紹了
springboot Java实现多文件的zip压缩操作 + 通过浏览器下载文件的两种方式
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
注只適配utf-8的場景,待完善!
壓縮為zip文件
2.1 通過瀏覽器下載文件(返回文件流) - 方式一
/*** 功能:壓縮多個文件,輸出壓縮后的zip文件流* @param srcfile:源文件列表* @param zipFileName:壓縮后的文件名* @return*/ @GetMapping(value = "/downzip") public ResponseEntity<byte[]> zipFiles(File[] srcfile, String zipFileName) {byte[] buf = new byte[1024];// 獲取輸出流ByteArrayOutputStream bos = new ByteArrayOutputStream();try {// ZipOutputStream類:完成文件或文件夾的壓縮ZipOutputStream out = new ZipOutputStream(bos);for (int i = 0; i < srcfile.length; i++) {// 此處可用任意其他輸入流將FileInputStream取代,outputStream為其他步驟的輸出流// ByteArrayInputStream in = new ByteArrayInputStream(outputStream.toByteArray());FileInputStream in = new FileInputStream(srcfile[i]);// 給列表中的文件單獨命名out.putNextEntry(new ZipEntry(srcfile[i].getName()));int len;while ((len = in.read(buf)) > 0) {out.write(buf, 0, len);}out.closeEntry();in.close();}out.close();bos.close();System.out.println("壓縮完成.");} catch (Exception e) {e.printStackTrace();}// 設(shè)置http響應(yīng)頭HttpHeaders header = new HttpHeaders();header.add("Content-Disposition", "attachment;filename=" + zipFileName + ".zip");return new ResponseEntity<byte[]>(bos.toByteArray(), header, HttpStatus.CREATED); }2.2 通過瀏覽器下載文件(返回文件流) - 方式二
/*** 功能:壓縮多個文件,輸出壓縮后的zip文件流* @param srcfile:源文件列表* @param zipFileName:壓縮后的文件名* @param response: Http響應(yīng)*/ @GetMapping(value = "/downzip") public void zipFiles(File[] srcfile, String zipFileName, HttpServletResponse response) {byte[] buf = new byte[1024];// 獲取輸出流BufferedOutputStream bos = null;try {bos = new BufferedOutputStream(response.getOutputStream());} catch (IOException e) {e.printStackTrace();}try {response.reset(); // 重點突出// 不同類型的文件對應(yīng)不同的MIME類型response.setContentType("application/x-msdownload");response.setCharacterEncoding("utf-8");response.setHeader("Content-disposition", "attachment;filename=" + zipFileName + ".zip");// ZipOutputStream類:完成文件或文件夾的壓縮ZipOutputStream out = new ZipOutputStream(bos);for (int i = 0; i < srcfile.length; i++) {FileInputStream in = new FileInputStream(srcfile[i]);// 給列表中的文件單獨命名out.putNextEntry(new ZipEntry(srcfile[i].getName()));int len;while ((len = in.read(buf)) > 0) {out.write(buf, 0, len);}out.closeEntry();in.close();}out.close();bos.close();System.out.println("壓縮完成.");} catch (Exception e) {e.printStackTrace();} }以上兩種方式,都是以輸出文件流的形式,通過瀏覽器端進(jìn)行下載,不同的是,第一種將流直接通過接口返回,第二種也是比較常見的一種,將文件流通過response進(jìn)行輸出,兩種方式均可,這里留存記錄下。
解壓縮zip文件
總結(jié)
以上是生活随笔為你收集整理的springboot Java实现多文件的zip压缩操作 + 通过浏览器下载文件的两种方式的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: IntelliJ IDEA 2020修改
- 下一篇: 启动vue项目失败,报错Failed a