使用ruoyi框架实现文件下载
前端发送请求,后端接收到之后从文件服务器取出文件返回文件流给前端
后端接口
@PostMapping("/download")
public void download(HttpServletResponse response,TestReportFile file) {
try {
// 获取文件数据
byte[] bytes = minioSupportUtil.downLoadFile(Paths.get(new URI(file.getFilePath()).getPath()).getFileName().toString(), MinioSupportUtil.REPORT_BUCKET);
if (bytes == null || bytes.length == 0) {
response.sendError(HttpServletResponse.SC_NOT_FOUND, "文件内容为空");
return;
}
// 设置响应头,指定文件类型
response.setContentType("application/octet-stream");
response.setCharacterEncoding("UTF-8");
// 指定下载的文件名
String fileName = file.getFileName();
String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString());
// 设置 Content-Disposition 让浏览器下载
response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedFileName + "\"");
// 写入文件流到响应输出
OutputStream outputStream = response.getOutputStream();
outputStream.write(bytes);
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("文件下载失败", e);
} catch (URISyntaxException e) {
e.printStackTrace();
throw new RuntimeException("文件路径解析失败", e);
}
}
前端代码(使用ruoyi封装的download)
this.download('data/reportfile/download',
requestParam
, row.fileName) //第一个参数是后端接口路径,第二个参数是请求参数,第三个参数下载的文件名

浙公网安备 33010602011771号