java實現阿里雲(oss)多檔案獲取並壓縮成zip格式下載
阿新 • • 發佈:2021-01-07
package com.wei.common.web.api; import com.aliyun.oss.OSSClient; import com.aliyun.oss.model.OSSObject; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletResponse; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.URLEncoder; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import static org.springframework.util.ObjectUtils.isEmpty; @Api(description = "檔案下載-相關介面") @Slf4j @RestController @RequestMapping("/test/filedownload") public class Test { @Autowired private OSSClient ossClient; /** * 參考:阿里雲(oss)官網api地址 * https://help.aliyun.com/product/31815.html */ @ApiOperation(value = "檔案壓縮下載", httpMethod = "GET", notes = "檔案壓縮下載") @RequestMapping(value = "zipDownload") public void zipDownload(HttpServletResponse response){ // 設定強制下載不開啟 response.setContentType("application/force-download"); ZipOutputStream zos = null; BufferedInputStream bis = null; BufferedOutputStream out = null; byte[] buffer = new byte[100 * 1024]; ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { String key = "376058d3dfc338c555cf308f8a2deb52.jpg*圖片測試.jpg,d41d8cd98f00b204e9800998ecf8427e.docx*excel測試.xlsx,"; if(!isEmpty(key)){ String zipName = "壓縮包名稱.zip"; // 用於將資料壓縮成Zip檔案格式 zos = new ZipOutputStream(baos); String[] keylist = key.split(","); for (String ossfile : keylist) { String type=ossfile.substring(0, ossfile.indexOf("*")); String name=ossfile.substring(type.length()+1, ossfile.length()); //bucketName需改為自己的bucketName OSSObject ossObject = ossClient.getObject("bucketName", type); bis = new BufferedInputStream(ossObject.getObjectContent()); zos.putNextEntry(new ZipEntry(name)); int i = bis.read(buffer); // 向壓縮檔案中輸出資料 while(i != -1){ zos.write(buffer, 0, i); i = bis.read(buffer); } zos.closeEntry(); } // 設定檔名 response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(zipName , "UTF-8")); out=new BufferedOutputStream(response.getOutputStream()); out.write(baos.toByteArray()); } } catch (Exception e) { e.printStackTrace(); } finally { //關閉流 if(zos != null){ try { zos.close(); } catch (IOException e) { e.printStackTrace(); } }if(bis != null){ try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } if(out != null){ try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
pom參考:
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.4.2</version>
</dependency>
//工作隨記,如若有誤,感謝指正。