Need to download a binary file as an excel in javascript - javascript

The issue is I want to download the response of the backend to the excel file and the response recognized as binary by talend API
here is my code
function get_excels(type, id) {
$.ajax({
method: "GET",
url: URL+id+"/"+type+"/excel",
success: function (result) {
var blob = new Blob([result], {
type: "application/json",
});
const link = document.createElement("a");
link.href = URL.createObjectURL(blob);
console.log(link.href);
link.download = `excel.xlsx`;
link.click();
},
});
}
<i onclick="get_excels('transactions', 1)" class="fas fa-file-excel"></i>
When I download the file, Microsoft excel throws this error
I need to know how can I handle the response from the API and download It as an excel file.
I will appreciate it If you can help me out.

There is no need to read the ajax content and then download it, you can let the browser directly download it which will handle both the filename and the extension - this is also more time/memory efficient.
function get_excels(type, id) {
const a = document.createElement('a')
a.href = URL+id+"/"+type+"/excel"
a.download = true // the browser will download the file and name it as the original file name and extension
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
}

Related

Converting arraybuffer to blob for downloading as excel file in Chrome

I am trying to create an excel file that is downloadable from both Firefox and Chrome from an Angular 2+ environment. I have it working perfectly in firefox, but everything i try just doesn't work in Chrome - it downloads the file but when you open it throws an error - "Excel cannot open this file because the file format or file extension is not valid..".
I've tried to set my post responseType as 'arrayBuffer' and then creating a blob then downloading that, with no success. I've tried responseType as:
1)'blob'
2)'blob' as 'json'
3)'blob' as 'blob'
and passing it through to my component that way. Nothing seems to work on Chrome, everything works on Firefox though.
Here are some of my functions i have used to try get Chrome to open this excel.
downloadBlob(data: Blob, fileName: string) {
//output file name
//detect whether the browser is IE/Edge or another browser
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
//To IE or Edge browser, using msSaveorOpenBlob method to download file.
window.navigator.msSaveOrOpenBlob(data, fileName);
} else {
//To another browser, create a tag to downlad file.
const url = window.URL.createObjectURL(data);
const a = document.createElement('a');
document.body.appendChild(a);
a.setAttribute('style', 'display: none');
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
a.remove();
}
}
blobToFile(data: Blob, fileName: string) {
const a = document.createElement('a');
document.body.appendChild(a);
a.style.display = 'none';
const url = window.URL.createObjectURL(data);
a.href = url; a.download = fileName; a.click();
window.URL.revokeObjectURL(url);
}
downloadArray(data, fileName: string) {
var blob = new window.Blob([data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
window.URL = window.URL || window.webkitURL;
var url = window.URL.createObjectURL(blob);
window.location.href = url;
}
I've even tried to use the FileSaver.js plugin to save my blob with the oneliner
saveAs('blob', 'filename');
but everything wont read when opening from chrome. Any suggestions would be much appreciated.
Consider removing revokeObjectURL(). This test works and downloads in Chrome: https://batman.dev/static/70844902/
function downloadBuffer(arrayBuffer, fileName) {
const a = document.createElement('a')
a.href = URL.createObjectURL(new Blob(
[ arrayBuffer ],
{ type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }
))
a.download = fileName
a.click()
}

Download csv file is not working in safari browser

I have used the below code to download a csv file
let url = "https://test.com/test/auth/files/download/86ccc28c-383f-4c84-ac0d-61478da2f62c/e60f7709-288a-424c-bb13-9ff4bb60bec1?platform=HTMLCLIENT&source=855ca910c9d347b69403cf1791bab97c&linktoken=be50f537833bf693d9e0a3ecb8432159db966ee6"
window.open(url);
Above code is working in all browsers except safari browser.
I have done the below work around,
let a = document.createElement('a');
a.target = '_self';
a.href = url;
a.download = 'test.csv';
document.body.appendChild(a);
a.click();
which is opening a file in new tab instead of downloading in safari. could any one help with this problem?
Reference: https://bugs.webkit.org/show_bug.cgi?id=167341
https://github.com/dotnetCarpenter/FileReader_Chrome
fetches as blob and converts to a datauri. Not suitable for large files, as the entire base64 encoded file has to be stored in memory.
fetch(url, {
method: 'get',
})
.then(response => response.blob())
.then(blob => {
const fileName = 'filename.csv'
if (navigator.msSaveBlob) { // IE11 and Edge 17-
navigator.msSaveBlob(blob, fileName)
} else { // every other browser
const reader = new FileReader()
reader.onloadend = () => {
const a = document.createElement("a")
a.href = reader.result
a.style.display = 'none'
a.download = fileName
document.body.appendChild(a)
a.click()
a.parentNode.removeChild(a)
}
reader.readAsDataURL(blob)
}
})
Can you post any of your html? I've had success forcing downloads of files by using the download attribute within an anchor tag.
<a href="http://www.this.link.com/csv_1.csv" download...

Enable download of file from server angular

I have already found a solution for csv files using blob but it doesn't seem to work with other files, I want to download the file regardless of the type. I will get the the url for the file on the page load,but using blob to preferred the click function is not working.
CopyUrl(urls) {
const a = document.createElement("a");
document.body.appendChild(a);
const blob: any = new Blob([urls], {
type: "octet/stream"
});
const url = window.URL.createObjectURL(blob);
a.href = url;
const data = "test" + ".mp4";
a.download = data;
a.click();
window.URL.revokeObjectURL(url);
return blob;
}
<a class="dropdown-item"
(click)="CopyUrl(mediaFiles.data[activeFileIndex].mediaFileResponse.sourceUrl)">Copy Url
</a>
Any help would be appreciated.
You can use file-saver. Send response as a byte stream from your backend and on button Click , make the following request
this.http.get(url,{ responseType: 'blob' }).subscribe((respBlob: any) => {
saveAs(respBlob, `file.pdf`)
});

Not able to Download ICS file in safari browser

I am trying to download ICS file in all the browsers.
I am able to download ICS file in chrome but not in safari. Here is the javascript code that i used.
if(isChrome)
{
var blob=new Blob([data]);
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download=fileName+".ics";
link.click()
}
if(!isChrome)
{
` alert("not chrome");
var downloadLink = document.createElement('a');
downloadLink.setAttribute('href', 'data:application/octet;charset=utf-8,' + escape(data));
var fileName = fileName+'.ics';
downloadLink.setAttribute('download', fileName);
var clk = document.createEvent("MouseEvent");
clk.initEvent("click", true, true);
downloadLink.dispatchEvent(clk);
document.body.appendChild(downloadLink);
downloadLink.dispatchEvent(clk);
//download(data, fileName+".ics", "text/calendar");
}
In Safari browser the generated file is getting downloaded but that file name is not getting appended. The filename i am getting is "Unknown" but the size of the file is 3KB and the content is there only the filename and extension is not getting added to the file.
Please let me know how i can solve this issue.
Thanks in advance
You should specify blob type. { type: 'text/calendar' }
const blob = new Blob([data], { type: 'text/calendar' });
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = filename + ".ics" ;
link.click();
Use this to download the file successfully, but you have to manually add it to the calendar. Safari does not include ics in a list of safe files and it will not be opened automatically.
If the problem is that you're using safari 10.1 or below the problem might be that it doesn't like the download attr.
http://caniuse.com/#feat=download

How to render data to Pdf once you have binary data from server?

I have post request which i am sending data to server and in response i have binary data from server for pdf ,Once i call pdfExport i see the response and Pdf file download but when i open that file its blank i dont see the data in pdf file. Any idea what i am doing wrong in below code...
So far tried code...
mainCtrl.js
$scope.pdfExport = function(){
var fileName = "test.pdf";
var a = document.createElement("a");
document.body.appendChild(a);
console.log("Pdf export..");
RiskHomePageService.getPdfExport($scope.dashboardGrid.options).then(function(result){
console.log("response server",result);
var file = new Blob([result.data], {type: 'application/force-download'});
console.log("after blob");
var fileURL = window.URL.createObjectURL(file);
console.log("file data",file);
a.href = fileURL;
a.download = fileName;
a.click();
});
}
mainService.js
getPdfExport: function(data){
return $http.post('/app/pdf/export',data).then(function(response){
return response;
});
}
try that
return $http.post('/app/pdf/export',data,{responseType:'arraybuffer'})

Categories