@GetMapping("readFileUrl")
@ApiOperation("下载文件")
@ApiImplicitParam(name = "fileUrl", value = "文件地址", required = true, dataType = "String", paramType = "body")
public void readFileUrl(HttpServletRequest request, HttpServletResponse response, @RequestParam String fileUrl)
throws ServletException, IOException {
if (StringUtils.isBlank(fileUrl)) {
response.setCharacterEncoding("utf-8");
response.getWriter().write(JSONObject.toJSON(new Result().error("参数错误")).toString());
return;
}
URL url = new URL(fileUrl);
String filename = fileUrl.substring((fileUrl.lastIndexOf('/') + 1));
BufferedInputStream in = null;
try {
// 这和上面两句一样的效果
in = new BufferedInputStream(url.openStream());
response.reset();
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition",
"attachment;filename=\"" + URLEncoder.encode(filename, "UTF-8") + "\"");
// 将网络输入流转换为输出流
int i;
while ((i = in.read()) != -1) {
response.getOutputStream().write(i);
}
} catch (IOException e) {
log.error("IO流异常",e);
} finally {
if (in != null ){
in.close();
}
response.getOutputStream().close();
}
}
07-04
588
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)