SpringBoot文件下載(多文件以zip形式,單文件格式不變)
- 初始化文件服務器(我的是minio)
- 文件下載
- # 樣例
- # # 單文件
- # # 多文件
初始化文件服務器(我的是minio)
private static MinioClient minioClient = null;private static String BUCKETNAME;public void init() {String endpoint = "endpoint";int port = 9000;String accessKey = "accessKey";String secretKey = "secretKey";boolean secure = false;try {minioClient = new MinioClient(endpoint, port, accessKey, secretKey, secure);if (!minioClient.bucketExists(BUCKETNAME)) {minioClient.makeBucket(BUCKETNAME);String config = "{\"Statement\":[{\"Action\":[\"s3:GetBucketLocation\",\"s3:ListBucket\"],\"Effect\":\"Allow\",\"Principal\":\"*\",\"Resource\":\"arn:aws:s3:::" + BUCKETNAME + "\"},{\"Action\":\"s3:GetObject\",\"Effect\":\"Allow\",\"Principal\":\"*\",\"Resource\":\"arn:aws:s3:::" + BUCKETNAME + "/*\"}],\"Version\":\"2012-10-17\"}";minioClient.setBucketPolicy(BUCKETNAME, config);}} catch (Exception var7) {throw new RuntimeException(var7);}}
文件下載
// fileName : /0/0/2025-9/合格率明細(2025-09).xlsxpublic void downInfo(HttpServletResponse response, String ... fileName) {if(fileName.length == 1){// 單文件下載downLoadOne(response,fileName[0]);}else{//多文件下載downZip(response,fileName);}}void downLoadOne(HttpServletResponse response, String filePath){try {InputStream fileStream = minioClient.getObject(BUCKETNAME, filePath);String baseName = FilenameUtils.getBaseName(filePath);response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(baseName, "UTF-8"));//文件流輸出OutputStream out = new BufferedOutputStream(response.getOutputStream());byte[] buffer = new byte[1024];int bytesRead;while ((bytesRead = fileStream.read(buffer)) != -1) {out.write(buffer, 0, bytesRead);}out.flush();out.close();fileStream.close();} catch (Exception err) {throw new RuntimeException("文件下載失敗", err);}}public void downZip(HttpServletResponse response,String ... fileName) {FileServer fileServer = FileServerFactory.get(null);// 設置響應頭response.setContentType("application/zip");response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"download.zip\"");// 創建流式響應try (ZipOutputStream zipOutputStream = new ZipOutputStream(response.getOutputStream())) {for (String filePath : fileName) {// 獲取文件流InputStream fileStream = minioClient.getObject(BUCKETNAME, filePath);// 創建ZIP條目String baseName = FilenameUtils.getBaseName(filePath);ZipEntry zipEntry = new ZipEntry(baseName);zipOutputStream.putNextEntry(zipEntry);// 寫入數據byte[] buffer = new byte[1024];int bytesRead;while ((bytesRead = fileStream.read(buffer)) != -1) {zipOutputStream.write(buffer, 0, bytesRead);}// 關閉條目和流zipOutputStream.closeEntry();fileStream.close();}zipOutputStream.finish();} catch (Exception e) {throw new RuntimeException("文件下載失敗", e);}}
# 樣例
# # 單文件
# # 多文件