作者:ChiuChiuLIN | 来源:互联网 | 2023-10-13 10:38
ZipOutputStream批量&OutputStream单个文件下载图片到本地1.使用ZipOutputStream批量打包文件到本地2.OutputStream单个文件下载图
ZipOutputStream批量&OutputStream单个文件下载图片到本地
- 1.使用ZipOutputStream批量打包文件到本地
- 2.OutputStream单个文件下载图片到本地
1.使用ZipOutputStream批量打包文件到本地
demo:
@RestController
@RequestMapping("download")
@Slf4j
public class DownLoadController {&#64;RequestMapping("test")public void test(HttpServletResponse response) {try {String nowTimeString &#61; "ll";String downloadFilename &#61; nowTimeString &#43; ".zip";downloadFilename &#61; URLEncoder.encode(downloadFilename, "UTF-8");response.setContentType("application/octet-stream");response.setHeader("Content-Disposition", "attachment;filename&#61;" &#43; downloadFilename);ZipOutputStream zos &#61; new ZipOutputStream(response.getOutputStream());ArrayList<String> files &#61; 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 &#61; 0; i < files.size(); i&#43;&#43;) {URL url &#61; new URL(files.get(i));zos.putNextEntry(new ZipEntry("ll/" &#43; i&#43; ".jpg"));
InputStream fis &#61; url.openConnection().getInputStream();byte[] buffer &#61; new byte[1024];int r &#61; 0;while ((r &#61; fis.read(buffer)) !&#61; -1) {zos.write(buffer, 0, r);}fis.close();}zos.flush();zos.close();} catch (Exception e) {log.error("下载失败", e);}}}
结果: 1.根据url分目录
2.自定义目录
2.OutputStream单个文件下载图片到本地
demo
&#64;RestController
&#64;RequestMapping("download")
&#64;Slf4j
public class DownLoadController {&#64;RequestMapping("singleQrCode")public void getSingleQrCode(HttpServletResponse response, String imgUrl) {try {String downloadFilename &#61; "new url";downloadFilename &#61; URLEncoder.encode(downloadFilename, "UTF-8");response.setContentType("application/octet-stream");response.setHeader("Content-Disposition", "attachment;filename&#61;" &#43; downloadFilename);response.setHeader("FileName", downloadFilename);OutputStream outputStream &#61; response.getOutputStream();URL url &#61; new URL(imgUrl);InputStream fis &#61; url.openConnection().getInputStream();byte[] buffer &#61; new byte[1024];int r;while ((r &#61; fis.read(buffer)) !&#61; -1) {outputStream.write(buffer, 0, r);}fis.close();outputStream.flush();outputStream.close();} catch (IOException e) {log.warn("品牌商二维码下载失败{}", JSON.toJSONString(imgUrl), e);}}