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>
//工作随记,如若有误,感谢指正。