@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();
}
http协议的IO流下载数据
最新推荐文章于 2022-02-17 14:25:14 发布