I am able to get the pdf in the new window with URL as
htts://mydomainname/410-8d9c-4883-86c5-d76c50a24a1d
I want to remove the auto generated blob name (410-8d9c-4883-86c5-d76c50a24a1d) in the generated URL and place my custom name link below
htts://mydomainname/filename
What modifications i need to do for below code
var file = new Blob([response], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
$window.open(fileURL);
Not sure exactly where this code lives for you, but here is a solution using XmlHttpRequest "onload".
oReq.onload = function(e) {
if (this.status === 200) {
const blob = new Blob([oReq.response], { type: "image/pdf"})
let a = document.createElement("a");
a.style = "display: none";
document.body.appendChild(a);
let url = window.URL.createObjectURL(blob);
a.href = url;
a.download = 'myFile.pdf'; // gives it a name via an a tag
a.click();
window.URL.revokeObjectURL(url);
} else {
// handler error eee
}
}
Basically rather than $window.open(fileURL); you need to programmatically create a anchor tag, setting its href with the window.URL.createObjectURL as youve done above.
Hope this helps,
Matt
Related
I've got a really simple line in my code that should trigger the download of a file created on the go.
window.open(window.URL.createObjectURL(new Blob(["Example of something being written into a file then downloaded"], {type: "text/plain"})));
But for some reason, this does not work. A new window starts appearing, and then suddenly disappears.
Any clue why this doesn't work?
EDIT: If I call
`window.location = window.URL.createObjectURL(new Blob(["Example of something being written into a file then downloaded"], {type: "text/plain"}));`
It opens the file. But nothing was downloaded.
Try this solution
var saveData = (function () {
var a = document.createElement("a");
document.body.appendChild(a);
return function () {
var data = "Your data...........",
fileName = "filename";
blob = new Blob(data, {type: "text/plain"}),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.text = "download file";
window.URL.revokeObjectURL(url);
};
}());
this will create new <a> element. You can download the file by clicking it.
This needs HTML 5 support and for more options, check answers for this question.
I'm trying to create a function where I can generate a blob .json file, which I then want to download.
I've checked around and found one way to do it.
function download_rapport(){
var data = geojson.features.map(function(row) { return row.properties; });
var json = JSON.stringify(data);
var blob = new Blob([json], {type: "application/json"});
var url = URL.createObjectURL(blob);
var a = document.createElement('a');
a.download = "backup.json";
a.href = url;
a.textContent = "Download backup.json";
document.getElementById('content_test').innerHTML = a.outerHTML;
// 'çontent_test' is a <div>
};
This works pretty well, however, this method uses a link to download. I would prefer to use a button, because it fits better with the rest of my application.
I used multiple methods to try and get a download button, but I always end up with a button that sends me to a new page with the data that I need shown as a string.
Is there a way to change my function so that it generates a downloadbutton instead of a downloadlink?
EDIT:
I've edited my code a bit with help from Midas. However, when I alter the data in my var json and try to download the "new" file, it will always download the "first" var json.
What I would like, is to be able to alter the var json data, and always download the "latest" version of it.
window.onload = function testreer() {
var data = geojson.features.map(function(row) { return row.properties; });
var json = JSON.stringify(data);
var blob = new Blob([json], {type: "application/json"});
var url = URL.createObjectURL(blob);
var a = document.createElement('a');
var b = document.createElement('button');
a.download = blob;
a.href = url;
b.innerText = 'Download';
document.getElementById('content_test').appendChild(b);
b.appendChild(a);
b.addEventListener('click', function() {
a.click();
});
}
Try this I have append a button in a link if that what you want.
function download_rapport(){
var data = geojson.features.map(function(row) { return row.properties; });
var json = JSON.stringify(data);
var blob = new Blob([json], {type: "application/json"});
var url = URL.createObjectURL(blob);
var a = document.createElement('a');
a.download = "backup.json";
a.href = url;
// 'çontent_test' is a <div>
var btn = document.createElement('button');
btn.value="download";
btn.innerHTML = "Download JSON";
a.appendChild(btn);
document.getElementById('content_test').innerHTML = a.outerHTML;
};
You can convert it it a button if you like
replace
document.createElement('a');
with
document.createElement("BUTTON");
I decided to give up on changing the link to a button. Instead, I will use CSS to style the link as a button. After checking around I found out that, although it is possible to change a link to a button, it is way faster to just use CSS to style it.
I edited my code a tiny bit by adding a.id = "downloadLink" to give the generated <a> an ID. This ID is then styled in my CSS file.
var a = document.createElement('a');
a.download = "backup.json";
a.href = url;
a.id = "downloadLink";
a.textContent = "Download backup.json";
Since a button has no href attribute like an a tag, you have to assign the desired action to the onclick event on the fly. An example is as follows:
window.onload = function()
{
var url = 'http://lipsum.com';
var btn = document.createElement('button');
btn.innerText = 'Download';
document.getElementById('content_test').appendChild(btn);
btn.addEventListener('click', function(){
window.location.href = url;
});
}
<div id="content_test"></div>
Edit:
Since the file is not coming from a server, you can create both the a tag and the button tag, triggering the link programmatically when the button is clicked:
window.onload = function() {
var url = 'http://lorempixel.com/400/300/technics/';
var a = document.createElement('a');
var b = document.createElement('button');
a.download = 'technics.jpg';
a.href = url;
b.innerText = 'Download';
document.getElementById('content_test').appendChild(b);
b.appendChild(a);
b.addEventListener('click', function() {
a.click();
});
}
<div id="content_test"></div>
However, In normal circumstances you would set Content-Disposition: attachment on the server side, to tell the browser that the file is to be downloaded.
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);
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();
}