OSS 工具类:
批量下载文件,下载成功为压缩文件:
准备:
相关开发数据参考链接:endpoint、accessKeyId、accessKeySecret、bucketName
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import com.google.common.collect.Maps;
import org.springframework.util.CollectionUtils;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class OSSUtil {
public static final String endpoint = "xxxxxxxxxxxxxxxx";
public static final String accessKeyId = "xxxxxxxxxxxxxxx";
public static final String accessKeySecret = "xxxxxxxxxxxxxxxxxxxxxx";
public static final String bucketName = "xxxxxxxxxxxxxxxx";
public static OSS ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
public static InputStream getStreamByObject(String filePath) {
try {
OSSObject ossObject = ossClient.getObject(bucketName, filePath);
return ossObject.getObjectContent();
} catch (Exception e) {
System.out.println("get oss object err." + e);
}
System.out.println("执行完成。");
return null;
}
public static void zipFile(List<String> fileList, ZipOutputStream zipOut) throws IOException {
if (CollectionUtils.isEmpty(fileList)) {
return;
}
for (String filePath : fileList) {
try (InputStream in = getStreamByObject(filePath)) {
zipOut.putNextEntry(new ZipEntry(getFileName(filePath)));
byte[] bytes = new byte[1024];
int len;
while ((len = in.read(bytes)) != -1) {
zipOut.write(bytes, 0, len);
}
zipOut.closeEntry();
}
}
}
private static String getFileName(String filePath) {
String filename = filePath.substring(filePath.lastIndexOf("/") + 1);
// String path = filePath.substring(0, filePath.lastIndexOf("/"));
return filename;
}
public static void main(String[] args) {
InputStream streamByObject = getStreamByObject("pictrue/lbxx.jpg");
System.out.println("streamByObject = " + streamByObject);
}
}
**
控制层:
文件集合 list 由自己去组装,
**
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.zip.ZipOutputStream;
@RestController
@RequestMapping(value = "/open")
public class OpenController {
@RequestMapping(value = "/download")
public void download(HttpServletResponse response) throws Exception{
List<String> list = new ArrayList<>();
list.add("pictrue/1.jpg");
list.add("pictrue/2.jpg");
list.add("pictrue/3.png");
list.add("pictrue/lbxx.jpg");
response.setCharacterEncoding("utf-8");
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
response.setHeader("Content-disposition", "attachment;filename=fileZip.zip");
try(ZipOutputStream outStream = new ZipOutputStream(response.getOutputStream())) {
OSSUtil.zipFile(list, outStream);
}
}
}