Related
In my application, i am trying to download html of current page which is with same domain name. I have written some method to download the html and it is downloading.
But, i have tried to open it in chrome as well as edge and it is not opening. But, in IE it is opening and displaying text of noscript tag (We're sorry but app doesn't work properly without JavaScript enabled.Please enable it to continue.).
I am inputting intranet site URL and clicking the download button. Here is my method below.
downloadHtml() {
let url = this.urlInput; // input text v-model value
fetch(url)
.then((res) => res.text())
.then((html) => this.downloadAsFile("report.html", html)); // by this name it is downloading
},
downloadAsFile(name, text) {
const link = this.createDownloadableLink(name, text);
const clickEvent = new MouseEvent("click");
link.dispatchEvent(clickEvent);
},
createDownloadableLink(fileName, content) {
let link = document.createElement("a");
link.href = 'data:attachment/text,' + encodeURIComponent(document.documentElement.outerHTML);
link.target = '_blank';
link.download = fileName;
return link;
},
**The problems are :
1. The app root signifies the public/index.html and that downloaded html is this one not the current page's html.
2. Chrome or Edge is not opening that html page even i checked browser is javascript enabled.
So, what i have to change the download the current page html?
The problem is that an HTML file in not an application/octet-stream file type. The mime type of an HTML page is text/html
I'm unsure of the way you try to create your download link. I don't have time to test it, but there is the way I do it usually using the createObjectURL API :
async function fetchHTML(url) {
let content = await fetch(url).then(resp => resp.text());
let file = new Blob([content],{type:'text/html'});
let href = window.URL.createObjectURL(file);
let a = document.createElement('a');
a.href = href;
a.setAttribute('download', 'report.html');
document.body.appendChild(a);
a.dispatchEvent(new MouseEvent('click'));
}
Another problem is that you don't append your link into the DOM in the code you provided. So the DOM cannot trigger your mouse event and so starting the download (it's needed by some browsers).
With the good mime type, the file in a proper format and a link in to the dom, it should be ok.
This question already has answers here:
How to create a file in memory for user to download, but not through server?
(22 answers)
Closed 2 years ago.
I have data that I want to write to a file, and open a file dialog for the user to choose where to save the file. It would be great if it worked in all browsers, but it has to work in Chrome. I want to do this all client-side.
Basically I want to know what to put in this function:
saveFile: function(data)
{
}
Where the function takes in data, has the user select a location to save the file, and creates a file in that location with that data.
Using HTML is fine too, if that helps.
A very minor improvement of the code by Awesomeness01 (no need for anchor tag) with addition as suggested by trueimage (support for IE):
// Function to download data to a file
function download(data, filename, type) {
var file = new Blob([data], {type: type});
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);
}
}
Tested to be working properly in Chrome, FireFox and IE10.
In Safari, the data gets opened in a new tab and one would have to manually save this file.
function download(text, name, type) {
var a = document.getElementById("a");
var file = new Blob([text], {type: type});
a.href = URL.createObjectURL(file);
a.download = name;
}
click here to download your file
<button onclick="download('file text', 'myfilename.txt', 'text/plain')">Create file</button>
And you would then download the file by putting the download attribute on the anchor tag.
The reason I like this better than creating a data url is that you don't have to make a big long url, you can just generate a temporary url.
This project on github looks promising:
https://github.com/eligrey/FileSaver.js
FileSaver.js implements the W3C saveAs() FileSaver interface in
browsers that do not natively support it.
Also have a look at the demo here:
http://eligrey.com/demos/FileSaver.js/
Choosing the location to save the file before creating it is not possible. But it is possible, at least in Chrome, to generate files using just JavaScript. Here is an old example of mine of creating a CSV file. The user will be prompted to download it. This, unfortunately, does not work well in other browsers, especially IE.
<!DOCTYPE html>
<html>
<head>
<title>JS CSV</title>
</head>
<body>
<button id="b">export to CSV</button>
<script type="text/javascript">
function exportToCsv() {
var myCsv = "Col1,Col2,Col3\nval1,val2,val3";
window.open('data:text/csv;charset=utf-8,' + escape(myCsv));
}
var button = document.getElementById('b');
button.addEventListener('click', exportToCsv);
</script>
</body>
</html>
For latest browser, like Chrome, you can use the File API as in this tutorial:
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
window.requestFileSystem(window.PERSISTENT, 5*1024*1024 /*5MB*/, saveFile, errorHandler);
function SaveBlobAs(blob, file_name) {
if (typeof navigator.msSaveBlob == "function")
return navigator.msSaveBlob(blob, file_name);
var saver = document.createElementNS("http://www.w3.org/1999/xhtml", "a");
var blobURL = saver.href = URL.createObjectURL(blob),
body = document.body;
saver.download = file_name;
body.appendChild(saver);
saver.dispatchEvent(new MouseEvent("click"));
body.removeChild(saver);
URL.revokeObjectURL(blobURL);
}
Tried this in the console, and it works.
var aFileParts = ['<a id="a"><b id="b">hey!</b></a>'];
var oMyBlob = new Blob(aFileParts, {type : 'text/html'}); // the blob
window.open(URL.createObjectURL(oMyBlob));
You cannot do this purely in Javascript. Javascript running on browsers does not have enough permission yet (there have been proposals) due to security reasons.
Instead, I would recommend using Downloadify:
A tiny javascript + Flash library that enables the creation and download of text files without server interaction.
You can see a simple demo here where you supply the content and can test out saving/cancelling/error handling functionality.
For Chrome and Firefox, I have been using a purely JavaScript method.
(My application cannot make use of a package such as Blob.js because it is served from a special engine: a DSP with a WWWeb server crammed in and little room for anything at all.)
function FileSave(sourceText, fileIdentity) {
var workElement = document.createElement("a");
if ('download' in workElement) {
workElement.href = "data:" + 'text/plain' + "charset=utf-8," + escape(sourceText);
workElement.setAttribute("download", fileIdentity);
document.body.appendChild(workElement);
var eventMouse = document.createEvent("MouseEvents");
eventMouse.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
workElement.dispatchEvent(eventMouse);
document.body.removeChild(workElement);
} else throw 'File saving not supported for this browser';
}
Notes, caveats, and weasel-words:
I have had success with this code in both Chrome and Firefox clients running in Linux (Maipo) and Windows (7 and 10) environments.
However, if sourceText is larger than a MB, Chrome sometimes (only sometimes) gets stuck in its own download without any failure indication; Firefox, so far, has not exhibited this behavior. The cause might be some blob limitation in Chrome. Frankly, I just don't know; if anybody has any ideas how to correct (or at least detect), please post. If the download anomaly occurs, when the Chrome browser is closed, it generates a diagnostic such as
This code is not compatible with Edge or Internet Explorer; I have not tried Opera or Safari.
StreamSaver is an alternative to save very large files without having to keep all data in the memory.In fact it emulates everything the server dose when saving a file but all client side with service worker.
You can either get the writer and manually write Uint8Array's to it or pipe a binary readableStream to the writable stream
There is a few example showcasing:
How to save multiple files as a zip
piping a readableStream from eg Response or blob.stream() to StreamSaver
manually writing to the writable stream as you type something
or recoding a video/audio
Here is an example in it's simplest form:
const fileStream = streamSaver.createWriteStream('filename.txt')
new Response('StreamSaver is awesome').body
.pipeTo(fileStream)
.then(success, error)
If you want to save a blob you would just convert that to a readableStream
new Response(blob).body.pipeTo(...) // response hack
blob.stream().pipeTo(...) // feature reference
Javascript has a FileSystem API. If you can deal with having the feature only work in Chrome, a good starting point would be: http://www.html5rocks.com/en/tutorials/file/filesystem/.
If for example you follow the link:
data:application/octet-stream;base64,SGVsbG8=
The browser will prompt you to download a file consisting of the data held as base64 in the hyperlink itself. Is there any way of suggesting a default name in the markup? If not, is there a JavaScript solution?
Use the download attribute:
<a download='FileName' href='your_url'>
The download attribute works on Chrome, Firefox, Edge, Opera, desktop Safari 10+, iOS Safari 13+, and not IE11.
Chrome makes this very simple these days:
function saveContent(fileContents, fileName)
{
var link = document.createElement('a');
link.download = fileName;
link.href = 'data:,' + fileContents;
link.click();
}
HTML only: use the download attribute:
<a download="logo.gif" href="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7">Download transparent png</a>
Javascript only: you can save any data URI with this code:
function saveAs(uri, filename) {
var link = document.createElement('a');
if (typeof link.download === 'string') {
link.href = uri;
link.download = filename;
//Firefox requires the link to be in the body
document.body.appendChild(link);
//simulate click
link.click();
//remove the link when done
document.body.removeChild(link);
} else {
window.open(uri);
}
}
var file = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'
saveAs(file, 'logo.gif');
Chrome, Firefox, and Edge 13+ will use the specified filename.
IE11, Edge 12, and Safari 9 (which don't support the download attribute) will download the file with their default name or they will simply display it in a new tab, if it's of a supported file type: images, videos, audio files, …
According to RFC 2397, no, there isn't.
Nor does there appear to be any attribute of the <a> element that you can use either.
However HTML5 has subsequently introduced the download attribute on the <a> element, although at the time of writing support is not universal (no MSIE support, for example)
I've looked a bit in firefox sources in netwerk/protocol/data/nsDataHandler.cpp
data handler only parses content/type and charset, and looks if there is ";base64"
in the string
the rfc specifices no filename and at least firefox handles no filename for it,
the code generates a random name plus ".part"
I've also checked firefox log
[b2e140]: DOCSHELL 6e5ae00 InternalLoad data:application/octet-stream;base64,SGVsbG8=
[b2e140]: Found extension '' (filename is '', handling attachment: 0)
[b2e140]: HelperAppService::DoContent: mime 'application/octet-stream', extension ''
[b2e140]: Getting mimeinfo from type 'application/octet-stream' ext ''
[b2e140]: Extension lookup on '' found: 0x0
[b2e140]: Ext. lookup for '' found 0x0
[b2e140]: OS gave back 0x43609a0 - found: 0
[b2e140]: Searched extras (by type), rv 0x80004005
[b2e140]: MIME Info Summary: Type 'application/octet-stream', Primary Ext ''
[b2e140]: Type/Ext lookup found 0x43609a0
interesting files if you want to look at mozilla sources:
data uri handler: netwerk/protocol/data/nsDataHandler.cpp
where mozilla decides the filename: uriloader/exthandler/nsExternalHelperAppService.cpp
InternalLoad string in the log: docshell/base/nsDocShell.cpp
I think you can stop searching a solution for now, because I suspect there is none :)
as noticed in this thread html5 has download attribute, it works also on firefox 20 http://www.whatwg.org/specs/web-apps/current-work/multipage/links.html#attr-hyperlink-download
The following Javascript snippet works in Chrome by using the new 'download' attribute of links and simulating a click.
function downloadWithName(uri, name) {
var link = document.createElement("a");
link.download = name;
link.href = uri;
link.click();
}
And the following example shows it's use:
downloadWithName("data:,Hello%2C%20World!", "helloWorld.txt")
No.
The entire purpose is that it's a datastream, not a file. The data source should not have any knowledge of the user agent handling it as a file... and it doesn't.
you can add a download attribute to the anchor element.
sample:
<a download="abcd.cer"
href="data:application/stream;base64,MIIDhTC......">down</a>
Using service workers, this is finally possible in the truest sense.
Create a fake URL. For example /saveAs/myPrettyName.jpg
Use URL in <a href, <img src, window.open( url ), absolutely anything that can be done with a "real" URL.
Inside the worker, catch the fetch event, and respond with the correct data.
The browser will now suggest myPrettyName.jpg even if the user opens the file in a new tab, and tries to save it there. It will be exactly as if the file had come from the server.
// In the service worker
self.addEventListener( 'fetch', function(e)
{
if( e.request.url.startsWith( '/blobUri/' ) )
{
// Logic to select correct dataUri, and return it as a Response
e.respondWith( dataURLAsRequest );
}
});
Look at this link:
http://lists.w3.org/Archives/Public/uri/2010Feb/0069.html
Quote:
It even works (as in, doesn't cause a problem) with ;base64 at the end
like this (in Opera at least):
data:text/plain;charset=utf-8;headers=Content-Disposition%3A%20attachment%3B%20filename%3D%22with%20spaces.txt%22%0D%0AContent-Language%3A%20en;base64,4oiaDQo%3D
Also there is some info in the rest messages of the discussion.
There is a tiny workaround script on Google Code that worked for me:
http://code.google.com/p/download-data-uri/
It adds a form with the data in it, submits it and then removes the form again. Hacky, but it did the job for me. Requires jQuery.
This thread showed up in Google before the Google Code page and I thought it might be helpful to have the link in here, too.
Here is a jQuery version based off of Holf's version and works with Chrome and Firefox whereas his version seems to only work with Chrome. It's a little strange to add something to the body to do this but if someone has a better option I'm all for it.
var exportFileName = "export-" + filename;
$('<a></a>', {
"download": exportFileName,
"href": "data:," + JSON.stringify(exportData, null,5),
"id": "exportDataID"
}).appendTo("body")[0].click().remove();
This one works with Firefox 43.0 (older not tested):
dl.js:
function download() {
var msg="Hello world!";
var blob = new File([msg], "hello.bin", {"type": "application/octet-stream"});
var a = document.createElement("a");
a.href = URL.createObjectURL(blob);
window.location.href=a;
}
dl.html
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8"/>
<title>Test</title>
<script type="text/javascript" src="dl.js"></script>
</head>
<body>
<button id="create" type="button" onclick="download();">Download</button>
</body>
</html>
If button is clicked it offered a file named hello.bin for download. Trick is to use File instead of Blob.
reference: https://developer.mozilla.org/de/docs/Web/API/File
(This answer has been made deprecated by newer technology, but will be kept here for historical interest.)
It's kind of hackish, but I've been in the same situation before. I was dynamically generating a text file in javascript and wanted to provide it for download by encoding it with the data-URI.
This is possible with minormajor user intervention. Generate a link right-click me and select "Save Link As..." and save as "example.txt". As I said, this is inelegant, but it works if you do not need a professional solution.
This could be made less painful by using flash to copy the name into the clipboard first. Of course if you let yourself use Flash or Java (now with less and less browser support I think?), you could probably find a another way to do this.
<a href=.. download=.. > works for left-click and right-click -> save link as..,
but <img src=.. download=.. > doesn't work for right-click -> save image as.. , "Download.jped" is suggested.
If you combine both:<a href=.. download=..><img src=..></a>
it works for left-click, right-click -> save link as.., right-click -> save image as..
You have to write the data-uri twice (href and src), so for large image files it is better to copy the uri with javascript.
tested with Chrome/Edge 88
var isIE = /*#cc_on!#*/false || !!document.documentMode; // At least IE6
var sessionId ='\n';
var token = '\n';
var caseId = CaseIDNumber + '\n';
var url = casewebUrl+'\n';
var uri = sessionId + token + caseId + url;//data in file
var fileName = "file.i4cvf";// any file name with any extension
if (isIE)
{
var fileData = ['\ufeff' + uri];
var blobObject = new Blob(fileData);
window.navigator.msSaveOrOpenBlob(blobObject, fileName);
}
else //chrome
{
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
window.requestFileSystem(window.TEMPORARY, 1024 * 1024, function (fs) {
fs.root.getFile(fileName, { create: true }, function (fileEntry) {
fileEntry.createWriter(function (fileWriter) {
var fileData = ['\ufeff' + uri];
var blob = new Blob(fileData);
fileWriter.addEventListener("writeend", function () {
var fileUrl = fileEntry.toURL();
var link = document.createElement('a');
link.href = fileUrl;
link.download = fileName;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}, false);
fileWriter.write(blob);
}, function () { });
}, function () { });
}, function () { });
}
You actually can achieve this, in Chrome and FireFox.
Try the following url, it will download the code that was used.
data:text/html;base64,PGEgaHJlZj0iZGF0YTp0ZXh0L2h0bWw7YmFzZTY0LFBHRWdhSEpsWmowaVVGVlVYMFJCVkVGZlZWSkpYMGhGVWtVaUlHUnZkMjVzYjJGa1BTSjBaWE4wTG1oMGJXd2lQZ284YzJOeWFYQjBQZ3BrYjJOMWJXVnVkQzV4ZFdWeWVWTmxiR1ZqZEc5eUtDZGhKeWt1WTJ4cFkyc29LVHNLUEM5elkzSnBjSFErIiBkb3dubG9hZD0idGVzdC5odG1sIj4KPHNjcmlwdD4KZG9jdW1lbnQucXVlcnlTZWxlY3RvcignYScpLmNsaWNrKCk7Cjwvc2NyaXB0Pg==
If for example you follow the link:
data:application/octet-stream;base64,SGVsbG8=
The browser will prompt you to download a file consisting of the data held as base64 in the hyperlink itself. Is there any way of suggesting a default name in the markup? If not, is there a JavaScript solution?
Use the download attribute:
<a download='FileName' href='your_url'>
The download attribute works on Chrome, Firefox, Edge, Opera, desktop Safari 10+, iOS Safari 13+, and not IE11.
Chrome makes this very simple these days:
function saveContent(fileContents, fileName)
{
var link = document.createElement('a');
link.download = fileName;
link.href = 'data:,' + fileContents;
link.click();
}
HTML only: use the download attribute:
<a download="logo.gif" href="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7">Download transparent png</a>
Javascript only: you can save any data URI with this code:
function saveAs(uri, filename) {
var link = document.createElement('a');
if (typeof link.download === 'string') {
link.href = uri;
link.download = filename;
//Firefox requires the link to be in the body
document.body.appendChild(link);
//simulate click
link.click();
//remove the link when done
document.body.removeChild(link);
} else {
window.open(uri);
}
}
var file = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'
saveAs(file, 'logo.gif');
Chrome, Firefox, and Edge 13+ will use the specified filename.
IE11, Edge 12, and Safari 9 (which don't support the download attribute) will download the file with their default name or they will simply display it in a new tab, if it's of a supported file type: images, videos, audio files, …
According to RFC 2397, no, there isn't.
Nor does there appear to be any attribute of the <a> element that you can use either.
However HTML5 has subsequently introduced the download attribute on the <a> element, although at the time of writing support is not universal (no MSIE support, for example)
I've looked a bit in firefox sources in netwerk/protocol/data/nsDataHandler.cpp
data handler only parses content/type and charset, and looks if there is ";base64"
in the string
the rfc specifices no filename and at least firefox handles no filename for it,
the code generates a random name plus ".part"
I've also checked firefox log
[b2e140]: DOCSHELL 6e5ae00 InternalLoad data:application/octet-stream;base64,SGVsbG8=
[b2e140]: Found extension '' (filename is '', handling attachment: 0)
[b2e140]: HelperAppService::DoContent: mime 'application/octet-stream', extension ''
[b2e140]: Getting mimeinfo from type 'application/octet-stream' ext ''
[b2e140]: Extension lookup on '' found: 0x0
[b2e140]: Ext. lookup for '' found 0x0
[b2e140]: OS gave back 0x43609a0 - found: 0
[b2e140]: Searched extras (by type), rv 0x80004005
[b2e140]: MIME Info Summary: Type 'application/octet-stream', Primary Ext ''
[b2e140]: Type/Ext lookup found 0x43609a0
interesting files if you want to look at mozilla sources:
data uri handler: netwerk/protocol/data/nsDataHandler.cpp
where mozilla decides the filename: uriloader/exthandler/nsExternalHelperAppService.cpp
InternalLoad string in the log: docshell/base/nsDocShell.cpp
I think you can stop searching a solution for now, because I suspect there is none :)
as noticed in this thread html5 has download attribute, it works also on firefox 20 http://www.whatwg.org/specs/web-apps/current-work/multipage/links.html#attr-hyperlink-download
The following Javascript snippet works in Chrome by using the new 'download' attribute of links and simulating a click.
function downloadWithName(uri, name) {
var link = document.createElement("a");
link.download = name;
link.href = uri;
link.click();
}
And the following example shows it's use:
downloadWithName("data:,Hello%2C%20World!", "helloWorld.txt")
No.
The entire purpose is that it's a datastream, not a file. The data source should not have any knowledge of the user agent handling it as a file... and it doesn't.
you can add a download attribute to the anchor element.
sample:
<a download="abcd.cer"
href="data:application/stream;base64,MIIDhTC......">down</a>
Using service workers, this is finally possible in the truest sense.
Create a fake URL. For example /saveAs/myPrettyName.jpg
Use URL in <a href, <img src, window.open( url ), absolutely anything that can be done with a "real" URL.
Inside the worker, catch the fetch event, and respond with the correct data.
The browser will now suggest myPrettyName.jpg even if the user opens the file in a new tab, and tries to save it there. It will be exactly as if the file had come from the server.
// In the service worker
self.addEventListener( 'fetch', function(e)
{
if( e.request.url.startsWith( '/blobUri/' ) )
{
// Logic to select correct dataUri, and return it as a Response
e.respondWith( dataURLAsRequest );
}
});
Look at this link:
http://lists.w3.org/Archives/Public/uri/2010Feb/0069.html
Quote:
It even works (as in, doesn't cause a problem) with ;base64 at the end
like this (in Opera at least):
data:text/plain;charset=utf-8;headers=Content-Disposition%3A%20attachment%3B%20filename%3D%22with%20spaces.txt%22%0D%0AContent-Language%3A%20en;base64,4oiaDQo%3D
Also there is some info in the rest messages of the discussion.
There is a tiny workaround script on Google Code that worked for me:
http://code.google.com/p/download-data-uri/
It adds a form with the data in it, submits it and then removes the form again. Hacky, but it did the job for me. Requires jQuery.
This thread showed up in Google before the Google Code page and I thought it might be helpful to have the link in here, too.
Here is a jQuery version based off of Holf's version and works with Chrome and Firefox whereas his version seems to only work with Chrome. It's a little strange to add something to the body to do this but if someone has a better option I'm all for it.
var exportFileName = "export-" + filename;
$('<a></a>', {
"download": exportFileName,
"href": "data:," + JSON.stringify(exportData, null,5),
"id": "exportDataID"
}).appendTo("body")[0].click().remove();
This one works with Firefox 43.0 (older not tested):
dl.js:
function download() {
var msg="Hello world!";
var blob = new File([msg], "hello.bin", {"type": "application/octet-stream"});
var a = document.createElement("a");
a.href = URL.createObjectURL(blob);
window.location.href=a;
}
dl.html
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8"/>
<title>Test</title>
<script type="text/javascript" src="dl.js"></script>
</head>
<body>
<button id="create" type="button" onclick="download();">Download</button>
</body>
</html>
If button is clicked it offered a file named hello.bin for download. Trick is to use File instead of Blob.
reference: https://developer.mozilla.org/de/docs/Web/API/File
(This answer has been made deprecated by newer technology, but will be kept here for historical interest.)
It's kind of hackish, but I've been in the same situation before. I was dynamically generating a text file in javascript and wanted to provide it for download by encoding it with the data-URI.
This is possible with minormajor user intervention. Generate a link right-click me and select "Save Link As..." and save as "example.txt". As I said, this is inelegant, but it works if you do not need a professional solution.
This could be made less painful by using flash to copy the name into the clipboard first. Of course if you let yourself use Flash or Java (now with less and less browser support I think?), you could probably find a another way to do this.
<a href=.. download=.. > works for left-click and right-click -> save link as..,
but <img src=.. download=.. > doesn't work for right-click -> save image as.. , "Download.jped" is suggested.
If you combine both:<a href=.. download=..><img src=..></a>
it works for left-click, right-click -> save link as.., right-click -> save image as..
You have to write the data-uri twice (href and src), so for large image files it is better to copy the uri with javascript.
tested with Chrome/Edge 88
var isIE = /*#cc_on!#*/false || !!document.documentMode; // At least IE6
var sessionId ='\n';
var token = '\n';
var caseId = CaseIDNumber + '\n';
var url = casewebUrl+'\n';
var uri = sessionId + token + caseId + url;//data in file
var fileName = "file.i4cvf";// any file name with any extension
if (isIE)
{
var fileData = ['\ufeff' + uri];
var blobObject = new Blob(fileData);
window.navigator.msSaveOrOpenBlob(blobObject, fileName);
}
else //chrome
{
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
window.requestFileSystem(window.TEMPORARY, 1024 * 1024, function (fs) {
fs.root.getFile(fileName, { create: true }, function (fileEntry) {
fileEntry.createWriter(function (fileWriter) {
var fileData = ['\ufeff' + uri];
var blob = new Blob(fileData);
fileWriter.addEventListener("writeend", function () {
var fileUrl = fileEntry.toURL();
var link = document.createElement('a');
link.href = fileUrl;
link.download = fileName;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}, false);
fileWriter.write(blob);
}, function () { });
}, function () { });
}, function () { });
}
You actually can achieve this, in Chrome and FireFox.
Try the following url, it will download the code that was used.
data:text/html;base64,PGEgaHJlZj0iZGF0YTp0ZXh0L2h0bWw7YmFzZTY0LFBHRWdhSEpsWmowaVVGVlVYMFJCVkVGZlZWSkpYMGhGVWtVaUlHUnZkMjVzYjJGa1BTSjBaWE4wTG1oMGJXd2lQZ284YzJOeWFYQjBQZ3BrYjJOMWJXVnVkQzV4ZFdWeWVWTmxiR1ZqZEc5eUtDZGhKeWt1WTJ4cFkyc29LVHNLUEM5elkzSnBjSFErIiBkb3dubG9hZD0idGVzdC5odG1sIj4KPHNjcmlwdD4KZG9jdW1lbnQucXVlcnlTZWxlY3RvcignYScpLmNsaWNrKCk7Cjwvc2NyaXB0Pg==
If for example you follow the link:
data:application/octet-stream;base64,SGVsbG8=
The browser will prompt you to download a file consisting of the data held as base64 in the hyperlink itself. Is there any way of suggesting a default name in the markup? If not, is there a JavaScript solution?
Use the download attribute:
<a download='FileName' href='your_url'>
The download attribute works on Chrome, Firefox, Edge, Opera, desktop Safari 10+, iOS Safari 13+, and not IE11.
Chrome makes this very simple these days:
function saveContent(fileContents, fileName)
{
var link = document.createElement('a');
link.download = fileName;
link.href = 'data:,' + fileContents;
link.click();
}
HTML only: use the download attribute:
<a download="logo.gif" href="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7">Download transparent png</a>
Javascript only: you can save any data URI with this code:
function saveAs(uri, filename) {
var link = document.createElement('a');
if (typeof link.download === 'string') {
link.href = uri;
link.download = filename;
//Firefox requires the link to be in the body
document.body.appendChild(link);
//simulate click
link.click();
//remove the link when done
document.body.removeChild(link);
} else {
window.open(uri);
}
}
var file = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'
saveAs(file, 'logo.gif');
Chrome, Firefox, and Edge 13+ will use the specified filename.
IE11, Edge 12, and Safari 9 (which don't support the download attribute) will download the file with their default name or they will simply display it in a new tab, if it's of a supported file type: images, videos, audio files, …
According to RFC 2397, no, there isn't.
Nor does there appear to be any attribute of the <a> element that you can use either.
However HTML5 has subsequently introduced the download attribute on the <a> element, although at the time of writing support is not universal (no MSIE support, for example)
I've looked a bit in firefox sources in netwerk/protocol/data/nsDataHandler.cpp
data handler only parses content/type and charset, and looks if there is ";base64"
in the string
the rfc specifices no filename and at least firefox handles no filename for it,
the code generates a random name plus ".part"
I've also checked firefox log
[b2e140]: DOCSHELL 6e5ae00 InternalLoad data:application/octet-stream;base64,SGVsbG8=
[b2e140]: Found extension '' (filename is '', handling attachment: 0)
[b2e140]: HelperAppService::DoContent: mime 'application/octet-stream', extension ''
[b2e140]: Getting mimeinfo from type 'application/octet-stream' ext ''
[b2e140]: Extension lookup on '' found: 0x0
[b2e140]: Ext. lookup for '' found 0x0
[b2e140]: OS gave back 0x43609a0 - found: 0
[b2e140]: Searched extras (by type), rv 0x80004005
[b2e140]: MIME Info Summary: Type 'application/octet-stream', Primary Ext ''
[b2e140]: Type/Ext lookup found 0x43609a0
interesting files if you want to look at mozilla sources:
data uri handler: netwerk/protocol/data/nsDataHandler.cpp
where mozilla decides the filename: uriloader/exthandler/nsExternalHelperAppService.cpp
InternalLoad string in the log: docshell/base/nsDocShell.cpp
I think you can stop searching a solution for now, because I suspect there is none :)
as noticed in this thread html5 has download attribute, it works also on firefox 20 http://www.whatwg.org/specs/web-apps/current-work/multipage/links.html#attr-hyperlink-download
The following Javascript snippet works in Chrome by using the new 'download' attribute of links and simulating a click.
function downloadWithName(uri, name) {
var link = document.createElement("a");
link.download = name;
link.href = uri;
link.click();
}
And the following example shows it's use:
downloadWithName("data:,Hello%2C%20World!", "helloWorld.txt")
No.
The entire purpose is that it's a datastream, not a file. The data source should not have any knowledge of the user agent handling it as a file... and it doesn't.
you can add a download attribute to the anchor element.
sample:
<a download="abcd.cer"
href="data:application/stream;base64,MIIDhTC......">down</a>
Using service workers, this is finally possible in the truest sense.
Create a fake URL. For example /saveAs/myPrettyName.jpg
Use URL in <a href, <img src, window.open( url ), absolutely anything that can be done with a "real" URL.
Inside the worker, catch the fetch event, and respond with the correct data.
The browser will now suggest myPrettyName.jpg even if the user opens the file in a new tab, and tries to save it there. It will be exactly as if the file had come from the server.
// In the service worker
self.addEventListener( 'fetch', function(e)
{
if( e.request.url.startsWith( '/blobUri/' ) )
{
// Logic to select correct dataUri, and return it as a Response
e.respondWith( dataURLAsRequest );
}
});
Look at this link:
http://lists.w3.org/Archives/Public/uri/2010Feb/0069.html
Quote:
It even works (as in, doesn't cause a problem) with ;base64 at the end
like this (in Opera at least):
data:text/plain;charset=utf-8;headers=Content-Disposition%3A%20attachment%3B%20filename%3D%22with%20spaces.txt%22%0D%0AContent-Language%3A%20en;base64,4oiaDQo%3D
Also there is some info in the rest messages of the discussion.
There is a tiny workaround script on Google Code that worked for me:
http://code.google.com/p/download-data-uri/
It adds a form with the data in it, submits it and then removes the form again. Hacky, but it did the job for me. Requires jQuery.
This thread showed up in Google before the Google Code page and I thought it might be helpful to have the link in here, too.
Here is a jQuery version based off of Holf's version and works with Chrome and Firefox whereas his version seems to only work with Chrome. It's a little strange to add something to the body to do this but if someone has a better option I'm all for it.
var exportFileName = "export-" + filename;
$('<a></a>', {
"download": exportFileName,
"href": "data:," + JSON.stringify(exportData, null,5),
"id": "exportDataID"
}).appendTo("body")[0].click().remove();
This one works with Firefox 43.0 (older not tested):
dl.js:
function download() {
var msg="Hello world!";
var blob = new File([msg], "hello.bin", {"type": "application/octet-stream"});
var a = document.createElement("a");
a.href = URL.createObjectURL(blob);
window.location.href=a;
}
dl.html
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8"/>
<title>Test</title>
<script type="text/javascript" src="dl.js"></script>
</head>
<body>
<button id="create" type="button" onclick="download();">Download</button>
</body>
</html>
If button is clicked it offered a file named hello.bin for download. Trick is to use File instead of Blob.
reference: https://developer.mozilla.org/de/docs/Web/API/File
(This answer has been made deprecated by newer technology, but will be kept here for historical interest.)
It's kind of hackish, but I've been in the same situation before. I was dynamically generating a text file in javascript and wanted to provide it for download by encoding it with the data-URI.
This is possible with minormajor user intervention. Generate a link right-click me and select "Save Link As..." and save as "example.txt". As I said, this is inelegant, but it works if you do not need a professional solution.
This could be made less painful by using flash to copy the name into the clipboard first. Of course if you let yourself use Flash or Java (now with less and less browser support I think?), you could probably find a another way to do this.
<a href=.. download=.. > works for left-click and right-click -> save link as..,
but <img src=.. download=.. > doesn't work for right-click -> save image as.. , "Download.jped" is suggested.
If you combine both:<a href=.. download=..><img src=..></a>
it works for left-click, right-click -> save link as.., right-click -> save image as..
You have to write the data-uri twice (href and src), so for large image files it is better to copy the uri with javascript.
tested with Chrome/Edge 88
var isIE = /*#cc_on!#*/false || !!document.documentMode; // At least IE6
var sessionId ='\n';
var token = '\n';
var caseId = CaseIDNumber + '\n';
var url = casewebUrl+'\n';
var uri = sessionId + token + caseId + url;//data in file
var fileName = "file.i4cvf";// any file name with any extension
if (isIE)
{
var fileData = ['\ufeff' + uri];
var blobObject = new Blob(fileData);
window.navigator.msSaveOrOpenBlob(blobObject, fileName);
}
else //chrome
{
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
window.requestFileSystem(window.TEMPORARY, 1024 * 1024, function (fs) {
fs.root.getFile(fileName, { create: true }, function (fileEntry) {
fileEntry.createWriter(function (fileWriter) {
var fileData = ['\ufeff' + uri];
var blob = new Blob(fileData);
fileWriter.addEventListener("writeend", function () {
var fileUrl = fileEntry.toURL();
var link = document.createElement('a');
link.href = fileUrl;
link.download = fileName;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}, false);
fileWriter.write(blob);
}, function () { });
}, function () { });
}, function () { });
}
You actually can achieve this, in Chrome and FireFox.
Try the following url, it will download the code that was used.
data:text/html;base64,PGEgaHJlZj0iZGF0YTp0ZXh0L2h0bWw7YmFzZTY0LFBHRWdhSEpsWmowaVVGVlVYMFJCVkVGZlZWSkpYMGhGVWtVaUlHUnZkMjVzYjJGa1BTSjBaWE4wTG1oMGJXd2lQZ284YzJOeWFYQjBQZ3BrYjJOMWJXVnVkQzV4ZFdWeWVWTmxiR1ZqZEc5eUtDZGhKeWt1WTJ4cFkyc29LVHNLUEM5elkzSnBjSFErIiBkb3dubG9hZD0idGVzdC5odG1sIj4KPHNjcmlwdD4KZG9jdW1lbnQucXVlcnlTZWxlY3RvcignYScpLmNsaWNrKCk7Cjwvc2NyaXB0Pg==