龙空技术网

Java批量下载图片并压缩为Zip,大家觉得这样写可以吗?

编程课堂 558

前言:

而今兄弟们对“java下载url图片”大体比较着重,同学们都想要知道一些“java下载url图片”的相关资讯。那么小编也在网上汇集了一些关于“java下载url图片””的相关知识,希望姐妹们能喜欢,咱们一起来学习一下吧!

问题:

在开发项目中,遇到前端传递多个图片URL到后端,实现图片的批量下载并压缩为Zip。

业务代码:

Controller

@PostMapping("/batchDownload")public void batchDownload(@RequestBody PassportDTO passportDTO, HttpServletResponse response) {    passportService.batchDownload(passportDTO, response);}

Service

public void batchDownload(PassportDTO passportDTO, HttpServletResponse response) {        String zipName = "通行证" + ".zip";        response.setHeader("content-type", "application/octet-stream");        response.setHeader("Content-disposition", "attachment;filename=" + zipName);        response.setCharacterEncoding("utf-8");        ZipOutputStream zipOutputStream = null;        try {            zipOutputStream = new ZipOutputStream(response.getOutputStream());            for (String pictureUrl : passportDTO.getPictureUrls()) {                String fileName = pictureUrl.substring(pictureUrl.lastIndexOf("/") + 1);                zipOutputStream.putNextEntry(new ZipEntry(fileName));                URL url = new URL(pictureUrl);                InputStream inputStream = new DataInputStream(url.openStream());                byte[] buff = new byte[1024];                int len;                while ((len = inputStream.read(buff)) != -1) {                    zipOutputStream.write(buff, 0, len);                }                zipOutputStream.closeEntry();                inputStream.close();            }        } catch (Exception e) {            e.printStackTrace();        } finally {            if (zipOutputStream != null) {                try {                    zipOutputStream.close();                } catch (IOException e) {                    e.printStackTrace();                }            }        }    }

说明:

通过图片路径创建输入流获取图片数据:

 File file = new File("/test/temp/vehicles/" + pictureUrl); InputStream inputStream = new FileInputStream(file);

通过图片URL路径创建输入流获取图片数据:

URL url = new URL(pictureUrl);InputStream inputStream = new DataInputStream(url.openStream());

路漫漫其修远兮,吾将上下而求索

译文:在追寻真理方面,前方的道路还很漫长,但我将百折不挠,不遗余力地去追求和探索。

如果您有什么好的想法与方法,欢迎在评论区留言,我们一起讨论~

标签: #java下载url图片