通过InputStream下载文件

本文详细讲解了如何通过HttpURLConnection实现文件下载,包括处理中文文件名、设置Content-Disposition以及异常处理。同时介绍了如何使用ZipArchiveOutputStream打包多个文件为压缩包的过程。

开头:本文着重通过InputStream流下载文件,通过get/post请求获取InputStream下载文件

核心代码:

其中uri:是文件的下载地址(在浏览器中可以直接通过此地址进行文件下载,在这里我们将该地址进行二次封装)

public void download(HttpServletResponse response) throws IOException {
   []byte buffer = download();
   // 清空response
   response.reset();
   // 设置response的Header
   response.addHeader("Content-Disposition", "attachment;filename=" +
           new String("filename".getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));//处理中文乱码
   OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
   response.setContentType("application/octet-stream");
   toClient.write(cadInfoVO.getBuffer());
   toClient.flush();
   toClient.close();
}
public byte[] download() {
   InputStream fis = null;
   try {
       fileName = URLEncoder.encode(fileName,"UTF-8");
       String uri = "文件下载地址"

       try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
           HttpGet httpGet = new HttpGet(uri);
           try (CloseableHttpResponse execute = httpClient.execute(httpGet)) {
               if (execute.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                   throw new RuntimeException("请求第三方接口失败");
               }
               HttpEntity entity = execute.getEntity();
               fis = entity.getContent();
               byte[] buffer = readInputStream(fis);

               fis.read(buffer);
               return buffer;
           }
       }
   } catch (IOException e) {
       throw new RuntimeException("下载失败",e);
   } finally {
       try {
           assert fis != null;
           fis.close();
       } catch (IOException e) {
           throw new RuntimeException("关闭流失败",e);
       }
   }
}
/**
 * 从输入流中获取数据
 * @param fis 输入流
 * @return
 * @throws Exception
 */
private byte[] readInputStream(InputStream fis) throws IOException {
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int len;
    while( (len=fis.read(buffer)) != -1 ){
        outStream.write(buffer, 0, len);
    }
    //fis.close();此处一定不能关闭流
    return outStream.toByteArray();
}

如果需要下载压缩包则使用下方代码替换第一段代码即可:

public void downloadAll(HttpServletResponse response) throws Exception {
    response.reset();
    response.setContentType("content-type:octet-stream;charset=UTF-8");
    response.setHeader("Content-Disposition", "attachment;filename=" +
            new String("filename".getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1)+".zip");
    ServletOutputStream out = response.getOutputStream();
    ZipArchiveOutputStream zous = new ZipArchiveOutputStream(out);
    zous.setUseZip64(Zip64Mode.AsNeeded);

    for(/**需要循环的文件列表*/) {
        byte[] buffer = download();
        //设置文件名
        ArchiveEntry entry = new ZipArchiveEntry("filename");
        zous.putArchiveEntry(entry);
        zous.write(buffer);
        zous.closeArchiveEntry();
    }
    zous.close();
}

如有不理解的地方欢迎来扰

评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值