编程语言
首页 > 编程语言> > JAVA批量打包下载URL图片

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接口地址即可开始下载

标签:fis,JAVA,String,批量,downloadFilename,URL,url,zos,response
来源: https://www.cnblogs.com/jcb1991/p/15754137.html