ZipOutputStream批量&OutputStream单个文件下载图片到本地
1.使用ZipOutputStream批量打包文件到本地
demo:
@RestController
@RequestMapping("download")
@Slf4j
public class DownLoadController {
@RequestMapping("test")
public void test(HttpServletResponse response) {
try {
String nowTimeString = "ll";
//文件的名称
String downloadFilename = nowTimeString + ".zip";
//转换中文否则可能会产生乱码
downloadFilename = URLEncoder.encode(downloadFilename, "UTF-8");
// 指明response的返回对象是文件流
response.setContentType("application/octet-stream");
// 设置在下载框默认显示的文件名
response.setHeader("Content-Disposition", "attachment;filename=" + downloadFilename);
ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
ArrayList<String> files = Lists.newArrayList(
"http://***/commodity_qrcode/qrcode_test/1983207019.jpg", "http://****/commodity_qrcode/qrcode_test/1979780937.jpg", "http://***/commodity_qrcode/qrcode_test/1979780935.jpg",
"http://***/commodity_qrcode/qrcode_test/1979780934.jpg", "http://****/commodity_qrcode/qrcode_test/1152809.jpg", "http://****/commodity_qrcode/qrcode_test/1152808.jpg",
"http://***/commodity_qrcode/qrcode_test/1152807.jpg",
"https://****/lll/test/2020-12/memo/f86dc6ba7a7642ac83f9f4409af2227e.jpg");
for (int i = 0; i < files.size(); i++) {
URL url = new URL(files.get(i));
//目录不能重复,否则会duplicate entry: ll/
//因此需要加个时间戳或者是uuid作为后缀
//也可以根据文件地址作为目录,会自动根据路径分区文件夹,一个/一个文件目录
zos.putNextEntry(new ZipEntry("ll/" + i+ ".jpg"));
//此时会自动分级目录,
// zos.putNextEntry(new ZipEntry(files.get(i));
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();
}
//强制把数据输出,清空缓存区,(必须要,因为一部分数据还在缓冲区)
//面向缓冲区的,不强制输出就关闭,数据可能不完整
//最后再关闭读写流调用close()就完成了
zos.flush();
//关闭输出流
zos.close();
} catch (Exception e) {
log.error("下载失败", e);
}
}
}
结果: 1.根据url分目录
2.自定义目录
2.OutputStream单个文件下载图片到本地
demo
@RestController
@RequestMapping("download")
@Slf4j
public class DownLoadController {
@RequestMapping("singleQrCode")
public void getSingleQrCode(HttpServletResponse response, String imgUrl) {
try {
String downloadFilename = "new url";
downloadFilename = URLEncoder.encode(downloadFilename, "UTF-8");
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + downloadFilename);
response.setHeader("FileName", downloadFilename);
OutputStream outputStream = response.getOutputStream();
URL url = new URL(imgUrl);
InputStream fis = url.openConnection().getInputStream();
byte[] buffer = new byte[1024];
int r;
while ((r = fis.read(buffer)) != -1) {
outputStream.write(buffer, 0, r);
}
fis.close();
outputStream.flush();
outputStream.close();
} catch (IOException e) {
log.warn("品牌商二维码下载失败{}", JSON.toJSONString(imgUrl), e);
}
}