问题
I have the following functions, I am trying to read a string from my MongoDB database which is an image decode it and send it to my Vue frontend to be downloaded.
@GetMapping(path = "/signature/{signatureId}", produces = MediaType.IMAGE_PNG_VALUE)
public byte[] downloadSignature(String signatureId) {
Signature signature = routeRepository.findBySignature(signature);
byte[] bytes = Base64.getDecoder().decode(signature.getSignature().getBytes(StandardCharsets.UTF_8));
// This try-catch just saves the signature locally for testing
// This works successfully so I know there isn't an issue with the byte array
try {
Files.write(bytes, new File("signature.png"));
} catch (IOException e) {
e.printStackTrace();
}
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_PNG);
headers.setContentLength(bytes.length);
headers.setCacheControl(CacheControl.noCache().getHeaderValue());
return new ResponseEntity<>(bytes, headers, HttpStatus.OK);
}
On my Vue frontend, I have the following
async downloadSignature(context, payload) {
await Route.downloadSignature(context.rootState.User.user, payload)
.then(({ data }) => {
const url = window.URL.createObjectURL(
new Blob([data], { type: "image/png" })
);
const link = document.createElement("a");
link.href = url;
link.setAttribute("download", "signature.png");
document.body.appendChild(link);
link.click();
})
.catch(() => {
Message.error("Something went wrong, please try again.");
});
}
Everything works successfully but when the file downloads there is an issue with the file and I cannot open it successfully
回答1:
With Axios, you need to specify in the request headers that the response type is a blob
Like so
Vue.axios.get(resource, { responseType: "blob" });
Pretty poor documentation on this.
来源:https://stackoverflow.com/questions/61461094/downloading-byte-array-from-spring-boot-to-vue-frontend