I was struggling to call API to get PDF/Excel files. I found complete solution which is working in all browsers. Here is the .net c# code:
And here is front end in React using axios and blob:[Route("api/queries")]
[HttpGet]
public string getFile()
{
WebClient Client = new WebClient();
Client.UseDefaultCredentials = true;
byte[] myDataBuffer = Client.DownloadData("URL");
string DocumentPath = Convert.ToBase64String(myDataBuffer);
return DocumentPath;
}
axios.get(fetchFileUrl)
.then((response) => {
var raw = window.atob(response.data);
var uint8Array = new Uint8Array(raw.length);
for (var i = 0; i < raw.length; i++) {
uint8Array[i] = raw.charCodeAt(i);
}
var newBlob = new Blob([uint8Array])
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(newBlob, fileName + '.xlsx');
console.log('ie', '11');
}
else {
const data = window.URL.createObjectURL(newBlob);
var link = document.createElement('a');
link.href = data;
link.download = fileName + '.xlsx';
link.click();
link.remove();
setTimeout(function () {
// For Firefox it is necessary to delay revoking the ObjectURL
window.URL.revokeObjectURL(data);
}, 100);
console.log('not ie', 'others');
}
console.log('end', new Date().toLocaleDateString("en-US") + ' ' + new Date().toLocaleTimeString("en-US"));
}).catch((error) => console.log(error));
No comments:
Post a Comment