通过url转文件流下载文件
@ApiOperation(value = "根据文件URL下载")
@GetMapping("/download")
@ResponseBody
public void checkDownload(@ApiParam("文件地址") @RequestParam("url") String url,
HttpServletResponse response) {
HttpURLConnection conn = null;
InputStream fis = null;
try {
File file = new File(url);
String ext = file.getName().substring(file.getName().lastIndexOf(".") + 1).toLowerCase();
StringBuffer buffername = new StringBuffer(url.substring(url.lastIndexOf("/")+1));
String filename = buffername.toString();
URL path = new URL(url);
conn = (HttpURLConnection) path.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5 * 1000);
fis = conn.getInputStream();
byte[] buffer = readInputStream(fis);
if (null != buffer && buffer.length > 0) {
response.reset();
response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
response.addHeader("Content-Length", "" + buffer.length);
OutputStream toClient = response.getOutputStream();
response.setContentType("application/octet-stream");
toClient.write(buffer);
toClient.flush();
toClient.close();
}
} catch (IOException ex) {
log.error("下载文件异常:", ex);
throw new RRException("下载异常,请稍后再试。");
} finally {
if (conn != null) {
conn.disconnect();
}
if (fis != null) {
try {
fis.close();
} catch (IOException ioe) {
log.error("下载文件->关闭流异常:", ioe);
}
}
}
}
private byte[] readInputStream(InputStream fis) throws IOException {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fis.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
fis.close();
return outStream.toByteArray();
}