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();
}
Related
This code works in all major browsers excpet in latest Opera 71 (Windows).
The behaviour is that no error or info shows up but the download never starts from end user perspective. In developer tools I see the binary content of the example pdf document in response tab.
It seems that the dynamic creation of tags is not working.
function downloadFile(urlToSend) {
var req = new XMLHttpRequest();
req.open("GET", urlToSend, true);
req.responseType = "blob";
req.onload = function (event) {
var URL = window.URL || window.webkitURL;
var contentType = req.getResponseHeader('content-type');
var blob = new Blob([req.response], {type: contentType});
var downloadUrl = URL.createObjectURL(blob);
var contentDisposition = req.getResponseHeader('content-disposition');
//var fileName = req.getResponseHeader("fileName") //if you have the fileName header available
var filename = 'doku.pdf'; //contentDisposition.match(/filename*="(.+)"/)[1];
if (filename) {
// use HTML5 a[download] attribute to specify filename
var a = document.createElement("a");
// safari doesn't support this yet
if (typeof a.download === 'undefined') {
window.location.href = downloadUrl;
} else {
//code which gets executed by Opera
a.href = downloadUrl;
a.download = filename;
document.body.appendChild(a);
a.click();
}
} else {
window.location.href = downloadUrl;
}
};
req.send();
}
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);
}
I want to download text file using javascript. I have tried with many scenarios but didn't get luck. Here is one example:
(function() {
var textFile = null,
makeTextFile = function(text) {
var data = new Blob([text], {
type: 'text/plain'
});
// If we are replacing a previously generated file we need to
// manually revoke the object URL to avoid memory leaks.
if (textFile !== null) {
window.URL.revokeObjectURL(textFile);
}
textFile = window.URL.createObjectURL(data);
return textFile;
};
var create = document.getElementById('create'),
textbox = document.getElementById('textbox');
create.addEventListener('click', function() {
var link = document.getElementById('downloadlink');
link.href = makeTextFile(textbox.value);
link.style.display = 'block';
}, false);
})();
<textarea id="textbox">Type something here</textarea>
<button id="create">Create file</button>
<a download="info.txt" id="downloadlink" style="display: none">Download</a>
please help.
Thank you all for response. I have found solution.
function download(data, filename, type) {
var a = document.createElement("a"),
file = new Blob([data], { type: type });
if (window.navigator.msSaveOrOpenBlob) // IE10+
window.navigator.msSaveOrOpenBlob(file, filename);
else { // Others
var 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);
}
}
A very fast and easy solution is to use FileSaver.js :
https://raw.githubusercontent.com/eligrey/FileSaver.js/master/FileSaver.js
Then it takes only 2 lines of code to download a txt file :
var blob = new Blob(["Hello World"], {type: "text/plain;charset=utf-8"});
saveAs(blob, "filename.txt");
This code example will display a dialog box to download a file named "filename.txt" containing the text "Hello world". Just replace this by the file name and the text content of your choice !
I have converted my existing data to text/csv and able to download the file in Chrome but when tried with Safari on iPad or Mac it opens a tab with name "unknown"/ "Untitled" . This is the code I am using -
var hiddenElement = document.createElement('a');
hiddenElement.href = 'data:text/csv,'+ encodeURI(response);
hiddenElement.target = '_blank';
hiddenElement.download = 'purchase.csv';
hiddenElement.click();
Is there anyway I can able to show the downloaded file as "purchase.csv" for safari.
Try this one
var a = document.createElement('a');
a.setAttribute("href",URL);
a.setAttribute("target", "_blank");
var dispatch = document.createEvent("HTMLEvents");
dispatch.initEvent("click", true, true);
a.dispatchEvent(dispatch);
return false;
IF the data is LOCAL -- Easy!
We just use window.URL.createObjectURL(). Let's set some globals...
//var response = Already defined by OP! Not sure what it is, but it's data to save.
var mimetype = "text/csv";
var filename = "purchase.csv";
Now we just set the header by means of the type argument to window.URL.createObjectURL()...
a.href = window.URL.createObjectURL(new Blob([response], {
encoding: "UTF-8",
type: mimetype + ";charset=UTF-8",
}));
IF the data is on the WEB -- Still easy, just more effort!
We can do this by means of XMLHTTPRequest() to download the file data, window.URL.createObjectURL() to cast the data to a blob type with MIME type headers, and then proceed normally in setting a.download = filename; and a.click();.
An abstract function for download file data directly to the JavaScript environment...
function load(url, callback) {
var xhr = new XMLHTTPRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) callback(xhr.responseText);
};
xhr.open("GET", url, true);
}
Then download the data, build the link, and click it:
load("site.com/t.txt", function (contents) {
var a = window.document.createElement('a');
a.href = window.URL.createObjectURL(new Blob([response], {
encoding: "UTF-8",
type: mimetype + ";charset=UTF-8",
}));
a.download = filename;
document.body.appendChild(a);
a.click();
a.remove();
});
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);