I am using react js on front end and spring boot for backend API's. Https Entity is returned from API controller. It is viewable on Postman but when I download it on browser in react app, it says image can't be opened because it may be damaged.
REST Controller
@PostMapping(value = "/receipt")
@ResponseStatus(value = HttpStatus.OK)
public HttpEntity<byte[]> generateTransactionReceipt(
@RequestBody DirectCardDebitTransactionRecordDTO directCardDebitTransactionRecord) throws DocumentException, IOException {
byte[] fileBytes = disputeReceiptService.printReceiptForDispute("Amount",
directCardDebitTransactionRecord);
HttpHeaders header = new HttpHeaders();
MediaType mediaType = MediaType.parseMediaType("image/jpeg");
header.setContentType(mediaType);
header.set("Content-Disposition",
"attachment; filename=receipt" + Calendar.getInstance().getTime().toInstant().toString()
+ ".jpg");
header.setContentLength(fileBytes.length);
return new HttpEntity<>(fileBytes, header);
}
React App
printReceipt = () => {
const {Host} = this.state.Host;
const {record} = this.state;
api.send({
url: `${Host}/api/v1/receipt`,
method: 'post',
responseType: 'arraybuffer',
headers: {
Accept: 'application/json',
},
data: {record},
skipAuthHeader: false,
}).then((response) => {
if (response.status === 200) {
console.log('Response')
console.log(response);
const data = response.data
const url = window.URL.createObjectURL(new Blob([response.data.json]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'receipt.jpeg');
document.body.appendChild(link);
link.click();
} else {
console.error(response);
notification.open({
type: 'error',
message: 'Error occurred in fetching the receipt',
duration: 3,
});
}
})
.catch((error) => {
console.log(error)
});
};
Postman
Request Headers
Content-Type: application/json
User-Agent: PostmanRuntime/7.36.1
Accept: */*
Cache-Control: no-cache
Postman-Token: 1ed415b2-38f3-4dcd-889c-00776a8f528a
Host: localhost:9504
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Content-Length: 7793
Request Body
Response Headers
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, PUT, PATCH
Access-Control-Max-Age: 3600
Access-Control-Allow-Headers: x-requested-with,x-auth-username,x-auth-password,x-auth-token,origin,accept,content-type,access-control-request-method,access-control-request-headers,authorization,Cache-Control
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Content-Type: image/jpeg
Content-Length: 669437
Date: Mon, 19 Feb 2024 06:02:48 GMT
Keep-Alive: timeout=60
Connection: keep-alive
What can done to properly download the image in the browser.