JAVA根據圖片路徑下載圖片並寫入ZIP

 public void downloadPic(HttpServletRequest request, HttpServletResponse response) throws IOException {
     
        List<Map<String, Object>> allSysApp = new ArrayList<>();
        List<String> imgUrls = new ArrayList<>();
        allSysApp.parallelStream().limit(3).forEach(m -> imgUrls.add((String) m.get("logo_img")));
        try {
            String downloadFilename = "中文.zip";//文件的名稱
            downloadFilename = URLEncoder.encode(downloadFilename, "UTF-8");//轉換中文否則可能會產生亂碼
            response.setContentType("application/octet-stream");// 指明response的返回對象是文件流
            response.setHeader("Content-Disposition", "attachment;filename=" + downloadFilename);// 設置在下載框默認顯示的文件名
            ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
            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("temp_download" + File.separator + i + ".jpg"));
                InputStream fis = getInputStreamByGet(url);
                byte[] buffer = new byte[1024];
                int r = 0;
                while ((r = fis.read(buffer)) != -1) {
                    zos.write(buffer, 0, r);
                }
                fis.close();
            }
            zos.flush();
            zos.close();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }


    // 通過get請求得到讀取器響應數據的數據流
    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;
    }

    /**
     * 得到圖片字節流 數組大小
     * */
    public static byte[] readStream(InputStream inStream) throws Exception{
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = -1;
        while((len = inStream.read(buffer)) != -1){
            outStream.write(buffer, 0, len);
        }
        outStream.close();
        inStream.close();
        return outStream.toByteArray();
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章