@Override
public void exportQrCode(YardPcPageParam param, HttpServletResponse response) {
QueryWrapper<YardEntity> queryWrapper = this.toPcListQuery(param);
List<YardEntity> yardEntityList = this.list(queryWrapper);
if (yardEntityList.size() == 0) {
throw new BizException("暂无数据!");
}
List<YardSimpleVo> yardSimpleVos = yardEntityList.stream().map(e -> {
YardSimpleVo vo = new YardSimpleVo();
vo.setName(e.getGroupId() + "大组" + e.getHouseNumber());
vo.setUrl(StringUtils.isEmpty(e.getQrCode()) ? "" : OssUtils.getUrlByOss(e.getQrCode()));
return vo;
}).collect(Collectors.toList());
String zipFileName = "yardsQrCode.zip";
//响应头的设置
response.reset();
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition", "attachment;filename=" + zipFileName);
ZipOutputStream zipOutputStream = null;
try {
zipOutputStream = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()));
zipOutputStream.setMethod(ZipOutputStream.DEFLATED); //设置压缩方法
} catch (Exception e) {
e.printStackTrace();
}
DataOutputStream os = null;
for (YardSimpleVo yardSimpleVo : yardSimpleVos) {
if (StringUtils.isEmpty(yardSimpleVo.getUrl())) {
continue;
}
String fileName = yardSimpleVo.getName() + ".jpg";
File file = new File("");
try {
URL url = new URL(yardSimpleVo.getUrl());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
InputStream is = conn.getInputStream();
file = FileUtils.inputStreamToFile(is, fileName);
} catch (Exception e) {
e.printStackTrace();
}
if (file.exists()) {
try {
assert zipOutputStream != null;
zipOutputStream.putNextEntry(new ZipEntry(fileName));
os = new DataOutputStream(zipOutputStream);
InputStream is = new FileInputStream(file);
byte[] b = new byte[100];
int length = 0;
while ((length = is.read(b)) != -1) {
os.write(b, 0, length);
}
is.close();
zipOutputStream.closeEntry();
} catch (IOException e) {
e.printStackTrace();
}
}
}
try {
if (os != null) {
os.flush();
os.close();
}
if (zipOutputStream != null) {
zipOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
需求:批量下载图片,并打包成zip导出
FileUtils:
import java.io.*;
public class FileUtils {
/**
* InputStream 转file
*/
public static File inputStreamToFile(InputStream ins, String name) throws Exception {
File file = new File(System.getProperty("java.io.tmpdir") + File.separator + name);
if (file.exists()) {
return file;
}
OutputStream os = new FileOutputStream(file);
int bytesRead;
int len = 8192;
byte[] buffer = new byte[len];
while ((bytesRead = ins.read(buffer, 0, len)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();
return file;
}
}