Java 网络图片打成压缩包并下载

网络图片打成压缩包并下载

    public void download(HttpServletResponse response) {
        List<Person> personList = personService.findAll();
        if (CollectionUtils.isNotEmpty(personList)) {
            ZipOutputStream out = null;
            try {
                String fileName = "人员头像.zip";
                response.setContentType("APPLICATION/OCTET-STREAM");
                response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("UTF-8"), "ISO-8859-1"));
                out = new ZipOutputStream(response.getOutputStream());
                ZipEntry zipEntry = null;
                URL url = null;
                for (Person person : personList) {
                    if (StringUtils.isNotBlank(person.getAvatar())) {
                        String fileUrl = "https://..." + person.getAvatar();
                        url = new URL(fileUrl);
                        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                        conn.connect();
                        int httpResult = conn.getResponseCode();
                        InputStream in = null;
                        if (httpResult != HttpURLConnection.HTTP_OK) {
                            continue;
                        } else {
                            in = conn.getInputStream();
                            String type = person.getAvatar().substring(person.getAvatar().lastIndexOf("."));
                            zipEntry = new ZipEntry(person.getPersonId() + "_" + person.getPersonName() + type);
                            out.putNextEntry(zipEntry);
                            int len;
                            byte[] buffer = new byte[1024];
                            while ((len = in.read(buffer)) > 0) {
                                out.write(buffer, 0, len);
                            }
                        }
                    }
                }
                out.closeEntry();
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

 

posted @ 2026-03-20 15:38  root-crypto  阅读(0)  评论(0)    收藏  举报