后端:
HttpHeaders headers = new HttpHeaders();
headers.setContentDispositionFormData("attachment", URLEncoder.encode(fileName,"UTF-8"));
headers.setContentLength(bytes.length);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.set("fileName", URLEncoder.encode(fileName,"UTF-8"));
headers.setAccessControlExposeHeaders(Arrays.asList(HttpHeaders.CONTENT_DISPOSITION,
HttpHeaders.CONTENT_LENGTH, HttpHeaders.CONTENT_TYPE));
return ResponseEntity.status(HttpStatus.SC_OK).headers(headers).body(bytes);
前端:
downloadFile(url, defaultFileName, data) {
axios({
url,
method: "post",
responseType: "blob",
data,
}).then((response) => {
let fileName;
const { data: body } = response;
const contentDisposition = response.headers["content-disposition"];
if (contentDisposition) {
var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
var matches = filenameRegex.exec(contentDisposition);
if (matches != null && matches[1]) {
fileName = matches[1].replace(/['"]/g, "");
}
}
if (body) {
let file = new Blob([body], {
type: "application/octet-stream",
});
var downloadElement = document.createElement("a");
var href = window.URL.createObjectURL(file);
downloadElement.href = href;
downloadElement.download = decodeURIComponent(fileName || defaultFileName);
document.body.appendChild(downloadElement);
downloadElement.click();
document.body.removeChild(downloadElement);
window.URL.revokeObjectURL(href);
} else {
}
});
},
|