现在我有个业务场景,就是需要把多张图片一起下载下来,怎么弄
我的思路是将数组存储多张图片, 用文件流的方式打包成压缩文件。
@GetMapping("/user/download/image")
@ApiOperation(value = "图片资料下载", notes = "传入下载用户id")
public void download(@RequestParam(value="id") Integer id,
@RequestParam(value="type") Integer type,
HttpServletResponse response){
try {
String downloadFilename = System.currentTimeMillis()+"_图片.zip";//文件的名称
downloadFilename = URLEncoder.encode(downloadFilename, "UTF-8");//转换中文否则可能会产生乱码
response.setContentType("application/octet-stream");// 指明response的返回对象是文件流
response.setHeader("Content-Disposition", "attachment;filename=" + downloadFilename);// 设置在下载框默认显示的文件名
ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
String [] files = imgArray(id,type);
if(null != files && files.length > 0) {
for (int i = 0; i < files.length; i++) {
URL url = new URL(files[i]);
zos.putNextEntry(new ZipEntry(i + ".jpg"));
InputStream fis = url.openConnection().getInputStream();
byte[] buffer = new byte[1024];
int r = 0;
while ((r = fis.read(buffer)) != -1) {
zos.write(buffer, 0, r);
}
fis.close();
}
}
zos.flush();
zos.close();
} catch (UnsupportedEncodingException e) {
log.info("下载用户资料图片出异常了",e.getMessage());
} catch (IOException e) {
// TODO Auto-generated catch block
log.info("下载用户资料图片出异常了",e.getMessage());
}
}