/**
* 文件下载
* @param fileId
*/
@Override
public void downloadMaterial(Long fileId, HttpServletResponse response) throws IOException {
//获取文件存储路径,此步骤省略,自己根据需求编写,或者直接把路径放在入参进行传递
//文件存储路径
String filePath;
File file = new File(filePath);
if (!file.exists()){
throw new ServiceException("文件不存在");
}
// 对文件名进行 URL 编码 commonSysFile.getOriginalFilename()文件原始名:文件名.后缀
String encodedFileName = URLEncoder.encode(commonSysFile.getOriginalFilename(), "UTF-8");
// 防止一些浏览器(如 Chrome)将 '+' 字符解码为空格,替换它
encodedFileName = encodedFileName.replaceAll("\\+", "%20");
// 设置响应头
response.reset();
response.setCharacterEncoding("UTF-8");
// 获取文件的 MIME 类型 对.png类型比较友好
String contentType = Files.probeContentType(Paths.get(filePath));
if (contentType == null) {
contentType =MediaType.APPLICATION_OCTET_STREAM_VALUE; // 默认为二进制流
}
// 设置 Content-Disposition,指定为附件下载,并附上文件名 filename*=utf-8考虑浏览器兼容问题,避免文件名中文乱码
response.addHeader("Content-Disposition", "attachment; filename=\"" + encodedFileName + "\"; filename*=utf-8''" + encodedFileName);
// 读取文件并将其写入到响应输出流 filePath文件存储路径:D:/abd/bcd/文件名.后缀
try (InputStream is = new BufferedInputStream(Files.newInputStream(Paths.get(filePath)))) {
OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) > 0) {
outputStream.write(buffer, 0, len);
}
outputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
附上postman测试结果: