Java下载多图片

Java下载多图片

 	//imgUrls 图片地址的集合
    public static void downloadPic(List<String> imgUrls, HttpServletResponse response) throws Exception {
        ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
        InputStream fis = null;
        try {
            String downloadFilename = "aptitude.zip";// 文件的名称
            downloadFilename = URLEncoder.encode(downloadFilename, "UTF-8");// 转换中文否则可能会产生乱码
            response.setContentType("application/octet-stream");// 指明response的返回对象是文件流
            response.setHeader("Content-Disposition","attachment;filename="+downloadFilename);// 设置在下载框默认显示的文件名

            String[] files = new String[imgUrls.size()];
            imgUrls.toArray(files);
            for (int i = 0; i < files.length; i++) {
                String url = files[i];
                zos.putNextEntry(new ZipEntry("download" + File.separator+i+ ".jpg"));
                fis = getInputStreamByGet(url);
                byte[] buffer = new byte[1024];
                int r = 0;
                while ((r = fis.read(buffer)) != -1) {
                    zos.write(buffer, 0, r);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            fis.close();
            zos.flush();
            zos.close();
        }
    }

    public static InputStream getInputStreamByGet(String url) {
        try {
            HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
            conn.setReadTimeout(5000);
            conn.setConnectTimeout(5000);
            conn.setRequestMethod("GET");

            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = conn.getInputStream();
                return inputStream;
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

你可能感兴趣的:(开发)