Reputation: 23
When I execute API in SwaggerUI it returns OK and I get download link and it works.
It's used for PDF files, this is the kind of data
And I need to download this using javascript, I tried converting it to base64 first and then downloading, but I'd never even get it to log in the console
For example
const binaryData = new Uint8Array([data.action_api_response]);
const base64Data = btoa(String.fromCharCode.apply(null, binaryData));
function arrayBufferToBase64(buffer) {
let binary = '';
const bytes = new Uint8Array(buffer);
const chunkSize = 1024;
for (let i = 0; i < bytes.length; i += chunkSize) {
const chunk = bytes.slice(i, i + chunkSize);
binary += String.fromCharCode.apply(null, chunk);
}
console.log(btoa(binary));
}
arrayBufferToBase64(buffer);
This returns an empty string.
I wanted to convert it to base64 first cause I already have a function that works with base64, but I've never done downloading byte array streams so not sure how to solve this.
Thanks in advance
Upvotes: 1
Views: 46
Reputation: 6858
You can create Blob storage via Blob API and tag it with link to be download in javascript and then download the file as per your desired file type.
Refer the code below for reference:
const byteArray = data.action_api_response;
const blob = new Blob([byteArray], { type: 'application/pdf' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = 'your-PDF-name-here.pdf';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
Upvotes: 0