下载文件服务器上文件,并且zip打包响应给客户端下载

不废话,看代码

方案:将文件下载到本地临时文件夹后,再打包后,将源文件及临时文件夹都进行删除

public static List<String> downloadToLocal(List<String> urls, HttpServletResponse response) {
   response.setContentType("application/x-msdownload;charset=utf-8");
   String rootPath = FILE_ADDRESS;
   File file = new File(rootPath);
   if (!file.exists()) {
      file.mkdirs();
   }
   List<String> fileList = new ArrayList<>();
   try {
      File f = null;
      FileOutputStream fos = null;
      InputStream inputStream = null;
      for (String url : urls) {
         URL u = new URL(url);
         HttpURLConnection conn = (HttpURLConnection) u.openConnection();
         // 设置超时间为3秒
         conn.setConnectTimeout(3 * 1000);
         // 防止屏蔽程序抓取而返回403错误
         conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
         // 得到输入流
         inputStream = conn.getInputStream();
         String fileName = url.substring(url.lastIndexOf("/") + 1);
         byte[] bytes = readInputStream(inputStream);

         fileList.add(rootPath + "//" + fileName);
         f = new File(rootPath + "//" + fileName);
         fos = new FileOutputStream(f);
         fos.write(bytes, 0, bytes.length);
      }
      if (fos != null) {
         fos.flush();
         fos.close();
      }
      if (inputStream != null) {
         inputStream.close();
      }
      return fileList;
   } catch (Exception e) {
      throw new ServiceException("Batch download file failed" + HttpDownloadUtil.class.getSimpleName() + "Batch download file failed");

   }
}


/**
 * 下载文件到制定路径
 *
 * @param fileList
 */
public static void zipFile(List<String> fileList, OutputStream out) {

   String zipName = "files.zip";
   //获取桌面地址
   //FileSystemView fsv = FileSystemView.getFileSystemView();
   //File com = fsv.getHomeDirectory();
   //保存压缩文件的地址
   //String zipPath = com.getPath() + "//" + zipName;
   BufferedInputStream bis = null;
   BufferedInputStream fis = null;
   try {
      //将压缩文件流输出到到桌面 需要直接下载的可以加个(//)注释的代码放开即可
      //ZipOutputStream zipOutput = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipPath)));
      //响应给客户端
      ZipOutputStream zipOutput = new ZipOutputStream(out);
      for (String str : fileList) {
         File file = new File(str);
         if (!file.exists()) {
            log.error("文件被删除");
            continue;
         }
         ZipEntry zEntry = new ZipEntry(file.getName());
         zipOutput.putNextEntry(zEntry);
         fis = new BufferedInputStream(new FileInputStream(file));
         bis = new BufferedInputStream(fis, 1024 * 10);
         byte[] buffer = new byte[1024];
         int read = 0;
         while ((read = bis.read(buffer)) != -1) {
            zipOutput.write(buffer, 0, read);
         }
      }
      zipOutput.closeEntry();
      if (bis != null) {
         bis.close();
      }
      if (fis != null) {
         fis.close();
      }
      zipOutput.close();  //关闭
      System.gc();//否则源文件删除时可能有问题(重点)
      if (deleteDir(new File(FILE_ADDRESS))) {
         log.info("源文件删除");
      }
   } catch (Exception e) {
      e.printStackTrace();
      log.error(e.getMessage());
   }

}


/**
	 * 从输入流中获取字节数组
	 *
	 * @param inputStream
	 * @return
	 * @throws IOException
	 */
	public static byte[] readInputStream(InputStream inputStream) throws IOException {
		byte[] buffer = new byte[1024];
		int len = 0;
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		while ((len = inputStream.read(buffer)) != -1) {
			bos.write(buffer, 0, len);
		}
		bos.close();
		return bos.toByteArray();
	}


@PostMapping("/downloadHttpFiles")
public void downloadHttpFiles(@ApiParam(value = "文件对象") @RequestBody FilePath filePaths, HttpServletResponse response) throws IOException {
   //设置response的header
   response.setContentType("application/zip");
   response.setHeader("Content-Disposition", "attachment;filename=files.zip");
   if (Func.isNotEmpty(filePaths)) {
      List<String> fileList = HttpDownloadUtil.downloadToLocal(filePaths.getFiles(), response);
      HttpDownloadUtil.zipFile(fileList, response.getOutputStream());
   }
}

转载注明出处

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值