前端文件下载方式
2025/4/1大约 2 分钟
GET 请求
方法一:写到
<a>标签href属性中
<a href="http://localhost:9527/download/file">下载文件</a>方法二:调用
window.open方法
const url = 'http://localhost:9527/download/file';
window.open(url);POST 请求
原生 JS 写法
const url = 'http://localhost:9527/download/file';
const data = {};
let xhr = new XMLHttpRequest();
xhr.open('POST', url);
xhr.setRequestHeader("Content-type", "application/json;charset=UTF-8");
xhr.responseType = "blob"; // arraybuffer 也可
xhr.send(
JSON.stringify(data)
);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
// 从响应头中取文件名
const fileName = xhr.getResponseHeader('Content-Disposition').split("=")[1];
// 从响应头中取相应内容类型
const mimeType = xhr.getResponseHeader('content-type');
const blob = new Blob([xhr.response], {
type: mimeType,
})
const url = window.URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.style.display = "none";
link.setAttribute("download", fileName);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
};JQuery 写法
JQuery旧版本(1.x) 封装的 xhr 对象,只提供了
responseText属性,而原始的XMLHttpRequest中的response属性并没有提供 所以这种写法仅适用于 JQuery 2.x+
const url = 'http://localhost:9527/download/file';
const data = {};
$.ajax({
url: url,
method: 'POST',
contentType: 'application/json;charset=UTF-8',
xhrFields: {
responseType: "blob" // arraybuffer
},
data: JSON.stringify(data),
success: function (data) {
responseData = data
},
error: function (err) {
console.log('请求失败')
},
complete: function (xhr) {
// 从响应头中取文件名
const fileName = xhr.getResponseHeader('Content-Disposition').split("=")[1];
// 从响应头中取相应内容类型
const mimeType = xhr.getResponseHeader('content-type');
const blob = new Blob([responseData], { type: mimeType })
const url = window.URL.createObjectURL(blob)
const link = document.createElement("a");
link.href = url;
link.style.display = "none";
link.setAttribute("download", fileName);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
});Axios 写法
const url = 'http://localhost:9527/download/file';
const data = {};
axios.post(url, data, {
responseType: 'blob' // arraybuffer 也可
}).then((response) => {
// 从响应头中取文件名
const fileName = (response.headers['content-disposition'].split("="))[1];
// 从响应头中取相应内容类型
const mimeType = response.headers['content-type'];
const blob = new Blob([response.data], { type: mimeType })
const url = window.URL.createObjectURL(blob)
const link = document.createElement("a");
link.href = url;
link.style.display = "none";
link.setAttribute("download", fileName);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
})后端代码
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/download")
public class FileDownloadController {
@RequestMapping("file")
public ResponseEntity<InputStreamResource> download() throws IOException {
String filePath = "D:\\Code\\webtest\\file\\log.xlsx";
FileSystemResource file = new FileSystemResource(filePath);
HttpHeaders headers = new HttpHeaders();
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
// 设置文件名
headers.add("Content-Disposition", String.format("attachment; filename=%s", file.getFilename()));
// 将 Content-Disposeition 属性暴露给客户端
// 没写会导致网络请求中可以看到但是实际运行或客户端控制台打印不出
headers.add("Access-Control-Expose-Headers", "Content-Disposition");
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
return ResponseEntity
.ok()
.headers(headers)
.contentLength(file.contentLength())
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(new InputStreamResource(file.getInputStream()));
}
}