@ApiOperation(value = "下载接口,传入文件全路径")
@GetMapping(value = "/downloadFile",produces="application/octet-stream")
public void fileDownload(HttpServletResponse response, @RequestParam("filePath") String filePath) {
// fileUrl为http或https链接
InputStream inputStream = null;
HttpURLConnection conn = null;
URL url;
BufferedInputStream bis = null;
OutputStream outputStream = null;
byte[] buffer = new byte[4096];
String fileName = filePath.substring(filePath.lastIndexOf("/")+1);
try {
String encodeName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString());
url = new URL(filePath);
conn = (HttpURLConnection) url.openConnection();
// 设置超时间为5秒
conn.setConnectTimeout(5 * 1000);
// 得到输入流
inputStream = conn.getInputStream();
response.reset();
response.setHeader("Content-Disposition", "attachment; filename=\"" + encodeName + "\"; filename*=utf-8''" + encodeName);
response.setContentType("application/octet-stream");
response.setContentLength((int)conn.getContentLength());
response.addHeader("Cache-Control", "no-cache, no-store, must-revalidate");
response.addHeader("charset", "utf-8");
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "No-cache");
response.setDateHeader("Expires", 0);
outputStream = new BufferedOutputStream(response.getOutputStream());
int len = 0;
while((len = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
outputStream.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
}
try {
if (inputStream != null) {
inputStream.close();
}
if(outputStream != null) {
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Java -通用文件下载接口
最新推荐文章于 2024-10-09 17:02:46 发布
该代码示例展示了一个使用Java处理HTTPGET请求的文件下载接口。通过HttpURLConnection连接远程文件URL,读取输入流并将其写入HTTP响应,以供客户端下载。设置了Content-Disposition头来指定文件名,并控制缓存策略。
摘要由CSDN通过智能技术生成