problem description
the front end of the project uses angular and the background springboot. The problem is that no matter how the backend modifies the file format, the file format downloaded at the front end is txt
I tested it with excle here, so I set MediaType.parseMediaType ("application/vnd.ms-excel")
related codes
Front end code:
service:
download(id: number): Observable<any> {
const url = "/resource/downloadFile?id=" + id;
return this.http.get<any>(url, {responseType: "blob"});
}
component:
download(id: number, name: string) {
console.log("download");
const arr = name.split(".");
console.log("Type is ", arr[1]);
this.resourceService.download(id).subscribe(
next => {
this.downFile(next, arr[0], arr[1]);
},
err => {
console.log("err", err);
}
);
}
downFile(result, fileName, fileType?) {
const data = result;
const blob = new Blob([data], {type: fileType});
console.log("Get type", fileType);
const objectUrl = URL.createObjectURL(blob);
const a = document.createElement("a");
a.setAttribute("style", "display:none");
a.setAttribute("href", objectUrl);
a.setAttribute("download", fileName);
a.click();
URL.revokeObjectURL(objectUrl);
}
background code
@GetMapping("/downloadFile")
fun downloadFile(id: Long): ResponseEntity<InputStreamResource> {
var resourceFile=fileService.findOne(id)
val filePath = resourceFile.url
println(""+filePath)
val file = FileSystemResource(filePath)
val headers = HttpHeaders()
headers.add("Cache-Control", "no-cache, no-store, must-revalidate")
headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", file.filename))
headers.add("Pragma", "no-cache")
headers.add("Expires", "0")
return ResponseEntity
.ok()
.headers(headers)
.contentLength(file.contentLength())
.contentType(MediaType.parseMediaType("application/vnd.ms-excel"))
.body(InputStreamResource(file.inputStream))
}
No error is reported at the front and back end. No matter what file you download, the download format is txt. What is the problem? Thank you