1. 程式人生 > >springboot專案中將伺服器檔案打包zip格式下載功能

springboot專案中將伺服器檔案打包zip格式下載功能

public class IOtools {

    /**
    * 將伺服器檔案存到壓縮包中
*/
public static void zipFile(List<File> files, ZipOutputStream outputStream) throws IOException, ServletException {
        try {
            int size = files.size();
// 壓縮列表中的檔案
for (int i = 0; i < size; i++) {
                File file = (File) files.get(i);
zipFile
(file, outputStream); } } catch (IOException e) { throw e; } } public static void zipFile(File inputFile, ZipOutputStream outputstream) throws IOException, ServletException { try { if (inputFile.exists()) { if (inputFile.isFile()) { FileInputStream inStream = new
FileInputStream(inputFile); BufferedInputStream bInStream = new BufferedInputStream(inStream); ZipEntry entry = new ZipEntry(inputFile.getName()); outputstream.putNextEntry(entry); final int MAX_BYTE = 10 * 1024 * 1024; // 最大的流為10M long streamTotal = 0; // 接受流的容量 int streamNum = 0; // 流需要分開的數量
int
leaveByte = 0; // 檔案剩下的字元數 byte[] inOutbyte; // byte陣列接受檔案的資料 streamTotal = bInStream.available(); // 通過available方法取得流的最大字元數 streamNum = (int) Math.floor(streamTotal / MAX_BYTE); // 取得流檔案需要分開的數量 leaveByte = (int) streamTotal % MAX_BYTE; // 分開檔案之後,剩餘的數量 if (streamNum > 0) { for (int j = 0; j < streamNum; ++j) { inOutbyte = new byte[MAX_BYTE]; // 讀入流,儲存在byte陣列 bInStream.read(inOutbyte, 0, MAX_BYTE); outputstream.write(inOutbyte, 0, MAX_BYTE); // 寫出流 } } // 寫出剩下的流資料 inOutbyte = new byte[leaveByte]; bInStream.read(inOutbyte, 0, leaveByte); outputstream.write(inOutbyte); outputstream.closeEntry(); // Closes the current ZIP entry // and positions the stream for // writing the next entry bInStream.close(); // 關閉 inStream.close(); } } else { throw new ServletException("檔案不存在!"); } } catch (IOException e) { throw e; } } public static void downloadFile(File file, HttpServletResponse response, boolean isDelete) { try { // 以流的形式下載檔案。 BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file.getPath())); byte[] buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); // 清空response response.reset(); OutputStream toClient = new BufferedOutputStream(response.getOutputStream()); response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().getBytes("UTF-8"),"ISO-8859-1")); toClient.write(buffer); toClient.flush(); toClient.close(); if(isDelete) { file.delete(); //是否將生成的伺服器端檔案刪除 } } catch (IOException ex) { ex.printStackTrace(); } } }