/**
* @param
* @param response
* @功能描述 为了单机版本服务的 下载文件:
* 单机版本获取文件地址 返回的http地址 会直接调用这个接口
*/
@PostMapping("/load")
public void load(@RequestBody LoadRequest request, HttpServletResponse response) throws Exception {
try {
String path = this.getClass().getClassLoader().getResource("").getPath();//注意getResource("")里面是空字符串
String filePath = path+"/revivefile/"+request.getFilename();
// String decodePath = Base64Util.decode(filePath);
File file = new File(filePath);
log.info("===file.download======filePath" + filePath + "=======decodePath" );
// 将文件写入输入流
FileInputStream fileInputStream = new FileInputStream(file);
InputStream fis = new BufferedInputStream(fileInputStream);
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
// 设置response的Header
response.setCharacterEncoding("UTF-8");
response.setContentType("multipart/form-data");
//Content-Disposition的作用:告知浏览器以何种方式显示响应返回的文件,用浏览器打开还是以附件的形式下载到本地保存
//attachment表示以附件方式下载 inline表示在线打开 "Content-Disposition: inline; filename=文件名.mp3"
// filename表示文件的默认名称,因为网络传输只支持URL编码的相关支付,因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(request.getFilename(), "UTF-8"));
response.setHeader("Content-type", "application-download");
// 告知浏览器文件的大小
response.addHeader("Content-Length", "" + file.length());
OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
outputStream.write(buffer);
outputStream.flush();
DownloadRecords records = new DownloadRecords();
records.setCreateUserId(request.getUserId());
records.setCreateTime(new Date());
records.setDownloadType(request.getFileType());
records.setId(System.currentTimeMillis());
recordsMapper.insertSelective(records);
} catch (IOException ex) {
ex.printStackTrace();
throw new Exception("download error");
}
}
java 获取 项目resource下文件以流的形式传给前端
最新推荐文章于 2024-12-21 15:21:19 发布