后端通过Spring的ResponseEntity或StreamingResponseBody返回文件流,设置Content-Disposition触发下载;前端使用axios发送请求并设responseType为blob,创建临时URL实现下载。1. 后端控制器校验文件路径安全性,防止路径穿越,小文件用Resource,大文件推荐StreamingResponseBody避免内存溢出。2. 前端从响应头解析文件名,处理中文乱码需后端URLEncoder编码,前端解码;IE兼容需msSaveBlob降级。3. 跨域时后端需配置CORS暴露Content-Disposition头。整个流程确保文件正确传输并触发浏览器下载行为。

在Spring项目中实现文件下载功能,前端使用JavaScript(JS)来触发下载请求,后端通过Spring控制器返回文件流。整个过程需要前后端配合,确保文件能正确传输并触发浏览器下载行为。
Spring Boot中可以通过ResponseEntity或直接使用HttpServletResponse输出文件流。以下是一个标准的文件下载接口示例:
代码示例:
<font face="Courier New,Courier,monospace">@GetMapping("/download")
public ResponseEntity<Resource> downloadFile(@RequestParam String fileName) throws IOException {
// 假设文件存放在resources/static/files/目录下
Path filePath = Paths.get("src/main/resources/static/files/" + fileName);
Resource resource = new UrlResource(filePath.toUri());
if (resource.exists()) {
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
.body(resource);
} else {
return ResponseEntity.notFound().build();
}
}说明:
../../etc/passwd)。由于普通的axios或fetch请求无法直接触发文件下载(它们会解析响应体),必须将响应类型设为blob,然后创建临时URL进行下载。
使用Axios下载文件的JS代码:
<font face="Courier New,Courier,monospace">function downloadFile(fileName) {
axios({
url: '/download?fileName=' + fileName,
method: 'GET',
responseType: 'blob', // 必须设为blob
}).then(response => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
// 从响应头获取文件名
const contentDisposition = response.headers['content-disposition'];
let filename = 'download';
if (contentDisposition) {
const match = contentDisposition.match(/filename="(.+)"/);
if (match != null && match[1]) {
filename = match[1];
}
}
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();
link.remove();
window.URL.revokeObjectURL(url); // 释放内存
}).catch(error => {
console.error('下载失败:', error);
});
}</font>关键点:
对于大文件,建议Spring后端使用StreamingResponseBody,避免一次性加载到内存:
<font face="Courier New,Courier,monospace">@GetMapping("/stream-download")
public ResponseEntity<StreamingResponseBody> streamDownload(@RequestParam String fileName) {
try {
Path path = Paths.get("src/main/resources/static/files/", fileName);
if (!Files.exists(path)) {
return ResponseEntity.notFound().build();
}
StreamingResponseBody stream = outputStream -> {
Files.copy(path, outputStream);
};
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"")
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(stream);
} catch (IOException e) {
return ResponseEntity.status(500).build();
}
}</font>前端JS代码无需修改,仍使用相同方式处理blob下载。
基本上就这些。只要后端正确返回文件流,前端用blob方式处理响应,就能实现稳定可靠的文件下载功能。
以上就是JS怎样在Spring中实现文件下载_JS在Spring中实现文件下载的详细步骤的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号