开头:本文着重通过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();
}
如有不理解的地方欢迎来扰