I want to share a simple approach for downloading files with JavaScript (ES6), React and a Spring Boot backend:
- Spring boot Rest Controller
Resource from org.springframework.core.io.Resource
@SneakyThrows
@GetMapping("/files/{filename:.+}/{extraVariable}")
@ResponseBody
public ResponseEntity<Resource> serveFile(@PathVariable String filename, @PathVariable String extraVariable) {
Resource file = storageService.loadAsResource(filename, extraVariable);
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"")
.body(file);
}
- React, API call using AXIOS
Set the responseType to arraybuffer to specify the type of data contained in the response.
export const DownloadFile = (filename, extraVariable) => {
let url = 'http://localhost:8080/files/' + filename + '/' + extraVariable;
return axios.get(url, { responseType: 'arraybuffer' }).then((response) => {
return response;
})};
Final step > downloading
with the help of js-file-download you can trigger browser to save data to file as if it was downloaded.
DownloadFile('filename.extension', 'extraVariable').then(
(response) => {
fileDownload(response.data, filename);
}
, (error) => {
// ERROR
});