http协议的IO流下载数据

本文详细介绍了一个文件下载API的实现过程,包括如何通过URL获取文件、处理文件名编码、设置响应头以实现文件下载以及资源释放等关键步骤。适用于需要在网络环境中提供文件下载服务的开发者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

@RequestMapping("/downloadfile")
   public void  downloadfile(String filePath,String token , String name) throws IOException {
   //获得请求文件名
   if(!StringUtils.isEmpty(token)){
      filePath = filePath+"&token="+token;
   }
   URL getUrl = new URL(filePath);
   // 返回不同的URLConnection子类的对象,这里URL是一个http,因此实际返回的是HttpURLConnection
   HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection();
   // 进行连接,但是实际上get request要在下一句的connection.getInputStream()函数中才会真正发到
   connection.connect();
   // 取得输入流,并使用Reader读取
   BufferedInputStream reader = new BufferedInputStream(connection.getInputStream());
   ServletOutputStream out = response.getOutputStream();
   //处理文件中的乱码问题
   byte[] bytes=name.getBytes("UTF-8");
   String name1 = new String(bytes, "ISO-8859-1");
   response.setCharacterEncoding("utf-8");
   response.setContentType("application/download");
   response.addHeader("Content-Disposition", "attachment;filename="+name1);
   int len = 0;
   byte[] buffer = new byte[1024];
   while ((len = reader.read(buffer)) != -1){
      out.write(buffer,0,len);
   }
   //释放资源
   connection.disconnect();
   out.close();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值