丨钢琴丶

JAVA批量打包下载URL图片

  /**
   * 给定一组url,将此集合地址下对应的资源下载到浏览器
   * @throws IOException
   */
  @ApiOperation("订单中心 下载商品图片")
  @RequestMapping(value = "/pub/downloadPic", method = RequestMethod.GET)
  public void downloadPic(HttpServletResponse response, String... url) throws Exception {
    List<String> urls = Arrays.asList(url);
    String error = "错误图片";
    String msg = "";
    ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
    try {
      String downloadFilename = "商品图片.zip";// 文件的名称
      downloadFilename = URLEncoder.encode(downloadFilename, "UTF-8");// 转换中文否则可能会产生乱码
      response.setContentType("application/octet-stream;charset=UTF-8");// 指明response的返回对象是文件流
      response.setHeader("Content-Disposition","attachment;filename="+downloadFilename);// 设置在下载框默认显示的文件名

      for (String url : urls) {
        msg = url;
        String imgName = url.substring(url.lastIndexOf("/"));
        zos.putNextEntry(new ZipEntry(imgName));
        InputStream fis = getInputStreamByGet("http://res2.xiaozu365.com" + url);
        byte[] bytes = new byte[1024];
        int len;
        while (true) {
          assert fis != null;
          if ((len = fis.read(bytes)) == -1) break;
          zos.write(bytes, 0, len);
        }
        fis.close();
      }
    } catch (Exception e) {
      error += ","+msg;
      e.printStackTrace();
      log.info("下载图片异常!error=" + error);
    } finally {
      zos.flush();
      zos.close();
    }
  }

在浏览器地址栏输入API接口地址即可开始下载

posted on 2021-12-31 18:23  丨钢琴丶  阅读(408)  评论(0编辑  收藏  举报

导航