[英]How to download a Spring Boot ByteArrayResource with axios?
I have a Spring Boot Rest application, and I want to pass a file from this to a Vue.js frontend with axios.我有一个 Spring 启动 Rest 应用程序,我想将一个文件从这个应用程序传递到 Vue.js 前端与 Z38C3717939C3CED286B.
Firstly I get some data from Google Cloud Storage and send it to my frontend like this:首先,我从 Google Cloud Storage 获取一些数据并将其发送到我的前端,如下所示:
Get from gcloud:从 gcloud 获取:
public ByteArrayResource downloadObject(String bucketName, String objectName) {
BlobId blob = BlobId.of(bucketName, objectName);
return new ByteArrayResource(storage.readAllBytes(blob));
}
Send with Spring boot:用 Spring 开机发送:
@RequestMapping(value = "/downloadFile", method= RequestMethod.GET)
public ResponseEntity<?> downloadFile(@RequestParam("fileRef") String fileRef){
String filename = "robot.png";
ByteArrayResource file = cloudStorage.downloadObject("bucket", "object");
return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"")
.contentLength(file.contentLength()).contentType(MediaType.APPLICATION_OCTET_STREAM).body(file);
}
Then I get the file in my frontend and try to save it, but the file is always corrupt.然后我在前端获取文件并尝试保存它,但文件总是损坏。
Axios Request: Axios 请求:
async downloadFile(fileRef){
await ApiService.downloadFile(fileRef).then( (res) => {
var blob=new Blob([res.data], {type: res.headers["content-type"]});
var fileDownload = require('js-file-download');
fileDownload(blob, 'robot.png');
}).catch((errr) => {
console.log(errr);
});
}
At the minute I've only tested this with a PNG file of a little robot, but I intend to be able to download JPGs, PDFS and MP3s as well.目前我只用一个小机器人的 PNG 文件对此进行了测试,但我打算也能够下载 JPG、PDFS 和 MP3。 Any help would be massively appreciated.
任何帮助将不胜感激。
I've also noticed that the headers I define in the Spring Boot response aren't visible from the frontend.我还注意到我在 Spring 引导响应中定义的标头从前端看不到。
Worked it out, I need to put responseType: 'blob'
in my axios request.解决了,我需要将
responseType: 'blob'
放入我的 axios 请求中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.