Using blob file download says File is corrupted - javascript

I am trying to download the file in angular js. For that, I have used the blob concept . File is getting download successfully but when I open that file it says File is corrupted.
var saveData = (function () {
var a = document.createElement("button");
document.body.appendChild(a);
a.style = "display: none";
return function (excelData, fileName) {
// var blob = b64toBlob(excelData, contentType);
blob = new Blob([excelData], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
};
}());

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()
}

Downloading large CSV file - href unintentionally truncating results

I'm attempting to download a CSV file using the href method, however it appears data is truncated when setting it to a href tag.
For IE I used msSaveBlob and that appears to be working correctly and all data is correctly downloaded.
if (navigator.msSaveBlob) { // IE 10+
navigator.msSaveBlob(new Blob([data], { type: 'text/csv;charset=utf-8;' }), filename);
}
//
var csvContent = "data:text/csv;charset=utf-8," + data;
var encodedUri = encodeURI(csvContent);
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
//
link.setAttribute("download", filename);
link.innerHTML = "CSV Link - Placeholder";
document.body.appendChild(link); // Required for FF
link.click();
These are relatively large files, 9k lines in excel (around 500kb).
Any ideas what I can do to stop this truncation? Should I use a different method? Thanks!
Solved using below answer:
download file using an ajax request
Essentially:
var file = new Blob([data], {type: 'text/csv;charset=utf-8;'});
if (window.navigator.msSaveOrOpenBlob) // IE10+
window.navigator.msSaveOrOpenBlob(file, filename);
else { // Others
var a = document.createElement("a"),
url = URL.createObjectURL(file);
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
setTimeout(function() {
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, 0);
}

blob not downloading in safari

i'm trying to download a csv file, however it seem to work in all browsers except safari? how come is that. in safari it is just showing it in the browser?
Here is my code:
var saveData = (function () {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
return function (data, fileName) {
var blob = new Blob([data], {type: "text/csv;charset=utf-8"}),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
setTimeout(function(){
window.URL.revokeObjectURL(url);
}, 100);
};
}());
Your using the HTML 5 download attribute on the anchor tag which Safari doesn't support.
http://caniuse.com/#feat=download
It's probably best to link to the file and set headers like so to tell the agent to download rather than display.
Content-Type: text/csv
Content-Disposition: attachment; filename="whatever.csv"

Creating Javascript Blob() with data from HTML Element. Then downloading it as a text file

I'm using an HTML5 site to create a log per-say within a textarea element. I need to pull the data from that area with the click of a button, and download it to my computer via a .txt file. How would I go about doing this if it is possible??
HTML:
<input type="button" onclick="newBlob()" value="Clear and Export">
Javascript:
function newBlob() {
var blobData = document.getElementById("ticketlog").value;
var myBlob = new Blob(blobData, "plain/text");
blobURL = URL.createObjectURL(myBlob);
var href = document.createElement("a");
href.href = blobURL;
href.download = myBlob;
href.id = "download"
document.getElementById("download").click();
}
I figure if I make the Blob, create a URL for it, map the URL to an "a" element then auto-click it then it should work in theory. Obviously I'm missing something though. Any help would be fantastic. 1st question on this site btw:p
The simplest way I've come up with is as follows:
function download(text, filename){
var blob = new Blob([text], {type: "text/plain"});
var url = window.URL.createObjectURL(blob);
var a = document.createElement("a");
a.href = url;
a.download = filename;
a.click();
}
download("this is the file", "text.txt");
List of possible blob filestypes: http://www.freeformatter.com/mime-types-list.html
const downloadBlobAsFile = (function closure_shell() {
const a = document.createElement("a");
return function downloadBlobAsFile(blob, filename) {
const object_URL = URL.createObjectURL(blob);
a.href = object_URL;
a.download = filename;
a.click();
URL.revokeObjectURL(object_URL);
};
})();
document.getElementById("theButton").addEventListener("click", _ => {
downloadBlobAsFile(new Blob(
[document.getElementById("ticketlog").value],
{type: "text/plain"}
), "result.txt");
});
The value of a download property of an <a> element is the name of the file to download, and the constructor of Blob is Blob(array, options).
I used this approach that doesn't involve creating an element and revokes the textFile after the browser showed the text file
var text = 'hello blob';
var blob = new Blob([text], { type: 'text/plain' });
let textFile = window.URL.createObjectURL(blob);
let window2 = window.open(textFile, 'log.' + new Date() + '.txt');
window2.onload = e => window.URL.revokeObjectURL(textFile);

JavaScript blob filename without link

How do you set the name of a blob file in JavaScript when force downloading it through window.location?
function newFile(data) {
var json = JSON.stringify(data);
var blob = new Blob([json], {type: "octet/stream"});
var url = window.URL.createObjectURL(blob);
window.location.assign(url);
}
Running the above code downloads a file instantly without a page refresh that looks like:
bfefe410-8d9c-4883-86c5-d76c50a24a1d
I want to set the filename as my-download.json instead.
The only way I'm aware of is the trick used by FileSaver.js:
Create a hidden <a> tag.
Set its href attribute to the blob's URL.
Set its download attribute to the filename.
Click on the <a> tag.
Here is a simplified example (jsfiddle):
var saveData = (function () {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
return function (data, fileName) {
var json = JSON.stringify(data),
blob = new Blob([json], {type: "octet/stream"}),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
};
}());
var data = { x: 42, s: "hello, world", d: new Date() },
fileName = "my-download.json";
saveData(data, fileName);
I wrote this example just to illustrate the idea, in production code use FileSaver.js instead.
Notes
Older browsers don't support the "download" attribute, since it's part of HTML5.
Some file formats are considered insecure by the browser and the download fails. Saving JSON files with txt extension works for me.
I just wanted to expand on the accepted answer with support for Internet Explorer (most modern versions, anyways), and to tidy up the code using jQuery:
$(document).ready(function() {
saveFile("Example.txt", "data:attachment/text", "Hello, world.");
});
function saveFile (name, type, data) {
if (data !== null && navigator.msSaveBlob)
return navigator.msSaveBlob(new Blob([data], { type: type }), name);
var a = $("<a style='display: none;'/>");
var url = window.URL.createObjectURL(new Blob([data], {type: type}));
a.attr("href", url);
a.attr("download", name);
$("body").append(a);
a[0].click();
window.URL.revokeObjectURL(url);
a.remove();
}
Here is an example Fiddle. Godspeed.
Same principle as the solutions above. But I had issues with Firefox 52.0 (32 bit) where large files (>40 MBytes) are truncated at random positions. Re-scheduling the call of revokeObjectUrl() fixes this issue.
function saveFile(blob, filename) {
if (window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob, filename);
} else {
const a = document.createElement('a');
document.body.appendChild(a);
const url = window.URL.createObjectURL(blob);
a.href = url;
a.download = filename;
a.click();
setTimeout(() => {
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
}, 0)
}
}
jsfiddle example
Late, but since I had the same problem I add my solution:
function newFile(data, fileName) {
var json = JSON.stringify(data);
//IE11 support
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
let blob = new Blob([json], {type: "application/json"});
window.navigator.msSaveOrOpenBlob(blob, fileName);
} else {// other browsers
let file = new File([json], fileName, {type: "application/json"});
let exportUrl = URL.createObjectURL(file);
window.location.assign(exportUrl);
URL.revokeObjectURL(exportUrl);
}
}
This is my solution. From my point of view, you can not bypass the <a>.
function export2json() {
const data = {
a: '111',
b: '222',
c: '333'
};
const a = document.createElement("a");
a.href = URL.createObjectURL(
new Blob([JSON.stringify(data, null, 2)], {
type: "application/json"
})
);
a.setAttribute("download", "data.json");
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
<button onclick="export2json()">Export data to json file</button>
saveFileOnUserDevice = function(file){ // content: blob, name: string
if(navigator.msSaveBlob){ // For ie and Edge
return navigator.msSaveBlob(file.content, file.name);
}
else{
let link = document.createElement('a');
link.href = window.URL.createObjectURL(file.content);
link.download = file.name;
document.body.appendChild(link);
link.dispatchEvent(new MouseEvent('click', {bubbles: true, cancelable: true, view: window}));
link.remove();
window.URL.revokeObjectURL(link.href);
}
}
Working example of a download button, to save a cat photo from an url as "cat.jpg":
HTML:
<button onclick="downloadUrl('https://i.imgur.com/AD3MbBi.jpg', 'cat.jpg')">Download</button>
JavaScript:
function downloadUrl(url, filename) {
let xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = "blob";
xhr.onload = function(e) {
if (this.status == 200) {
const blob = this.response;
const a = document.createElement("a");
document.body.appendChild(a);
const blobUrl = window.URL.createObjectURL(blob);
a.href = blobUrl;
a.download = filename;
a.click();
setTimeout(() => {
window.URL.revokeObjectURL(blobUrl);
document.body.removeChild(a);
}, 0);
}
};
xhr.send();
}
window.location.assign did not work for me. it downloads fine but downloads without an extension for a CSV file on Windows platform. The following worked for me.
var blob = new Blob([csvString], { type: 'text/csv' });
//window.location.assign(window.URL.createObjectURL(blob));
var link = window.document.createElement('a');
link.href = window.URL.createObjectURL(blob);
// Construct filename dynamically and set to link.download
link.download = link.href.split('/').pop() + '.' + extension;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
this is a good easy solution for it.
function downloadBloob(blob,FileName) {
var link = document.createElement("a"); // Or maybe get it from the current document
link.href = blob;
link.download = FileName;
link.click();
}

Categories