To handle the Received document using Axios, with data in the format of `octect-stream` which may appear strange like `PK something JbxfFGvddvbdfbVVH34365436fdkln` as its octet stream format, ensuring that creating a file with this data may lead to corruption. Using `{responseType: 'blob'}` will convert the data into a readable format.
axios.get("URL", {responseType: 'blob'})
.then((r) => {
let fileName = r.headers['content-disposition'].split('filename=')[1];
let blob = new Blob([r.data]);
window.saveAs(blob, fileName);
}).catch(err => {
console.log(err);
});
If you have attempted solutions that fail, such as trying to save a file as zip using window.saveAs(blob, 'file.zip')
, consider:
const downloadFile = (fileData) => {
axios.get(baseUrl+"/file/download/"+fileData.id)
.then((response) => {
console.log(response.data);
const blob = new Blob([response.data], {type: response.headers['content-type'], encoding:'UTF-8'});
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = 'file.zip';
link.click();
})
.catch((err) => console.log(err))
}
const downloadFile = (fileData) => {
axios.get(baseUrl+"/file/download/"+fileData.id)
.then((response) => {
console.log(response);
const blob = new Blob([response.data], {type:"application/octet-stream"});
window.saveAs(blob, 'file.zip')
})
.catch((err) => console.log(err))
}
function base64ToArrayBuffer(base64) {
var binaryString = window.atob(base64);
var binaryLen = binaryString.length;
var bytes = new Uint8Array(binaryLen);
for (var i = 0; i < binaryLen; i++) {
var ascii = binaryString.charCodeAt(i);
bytes[i] = ascii;
};
return bytes;
}
Alternatively, another succinct solution is:
window.open("URL")
This approach may cause unnecessary tabs to open and require users to allow popups to work with this code. For scenarios where multiple files need to be downloaded simultaneously, it is advisable to go with the first solution or explore other alternatives.