1、废话不多说,如下图所示
@ApiOperation("文件下载")
@GetMapping("/download")
public void download(@RequestParam("fileUrl") String fileUrl, @RequestParam("fileName") String fileName, HttpServletResponse response) throws IOException {
log.info("download--fileUrl: {},fileName: {}",fileUrl,fileName);
InputStream download = null;
ServletOutputStream outputStream = null;
try{
URL url = new URL(fileUrl);
// HttpURLConnection connection = (HttpURLConnection)url.openConnection();
// connection.setConnectTimeout(5*1000);
// connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
// download = connection.getInputStream();
download = url.openStream();
response.addHeader("Cache-Control", "no-cache, no-store, must-revalidate");
response.addHeader("charset", "utf-8");
response.addHeader("Pragma", "no-cache");
String encodeName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString());
response.addHeader("content-disposition", "attachment;fileName="+encodeName);
outputStream = response.getOutputStream();
outputStream.write(IOUtils.toByteArray(download));
}catch (Exception e){
log.error("文件下载失败",e);
}finally{
if(download != null){
download.close();
}
if(outputStream != null){
outputStream.close();
}
}
}
标签:outputStream,java,URL,fileName,download,fileUrl,null,response,下载
From: https://www.cnblogs.com/linhuaming/p/17374157.html