1. 程式人生 > 其它 >springboot檔案上傳下載的一天

springboot檔案上傳下載的一天

1.zip打包批量下載檔案,拿到即可用

@Slf4j
public class ZipDownloadUtil {
    /**
     * zip打包下載
     */
    public void zipDownload(HttpServletResponse response, String wordPath, String zipFileName, List<File> fileList) {
        //生成快取資料夾名
        String zipPath = wordPath + File.separator + "cache" + File.separator + zipFileName;
        
try { //建立zip輸出流 try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipPath))) { //宣告檔案集合用於存放檔案 byte[] buffer = new byte[1024]; //將檔案放入zip壓縮包 for (int i = 0; i < fileList.size(); i++) { File file
= fileList.get(i); try (FileInputStream fis = new FileInputStream(file)) { out.putNextEntry(new ZipEntry(file.getName())); int len; // 讀入需要下載的檔案的內容,打包到zip檔案 while ((len = fis.read(buffer)) > 0
) { out.write(buffer, 0, len); } out.closeEntry(); } } } //下載zip檔案 downFile(response,wordPath, zipFileName); } catch (Exception e) { log.error("檔案下載出錯", e); } finally { // zip檔案也刪除 List<File> fileList1 =new ArrayList<>(); fileList1.add(new File(zipPath)); deleteFile(fileList1); } } /** * 檔案下載 */ public void downFile(HttpServletResponse response,String wordPath, String zipFileName) { // zip檔案路徑 自己的路徑自定義哈 String path = wordPath + File.separator + "cache" + File.separator + zipFileName; try { File file = new File(path); if (file.exists()) { try (InputStream ins = new FileInputStream(path); BufferedInputStream bins = new BufferedInputStream(ins); OutputStream outs = response.getOutputStream(); BufferedOutputStream bouts = new BufferedOutputStream(outs)) { response.setContentType("application/x-download"); response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(zipFileName, "UTF-8")); int bytesRead = 0; byte[] buffer = new byte[1024]; while ((bytesRead = bins.read(buffer, 0, 1024)) != -1) { bouts.write(buffer, 0, bytesRead); } bouts.flush(); } } } catch (Exception e) { log.error("檔案下載出錯", e); } } /** * 刪除檔案 */ public void deleteFile(List<File> fileList) { for (File file : fileList) { if (file.exists()) { file.delete(); } } } }