Javascript 下载数据url文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3916191/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Download data url file
提问by Mikee
I'm playing with the idea of making a completely JavaScript-based zip/unzip utility that anyone can access from a browser. They can just drag their zip directly into the browser and it'll let them download all the files within. They can also create new zip files by dragging individual files in.
我正在考虑制作一个完全基于 JavaScript 的 zip/unzip 实用程序,任何人都可以从浏览器访问它。他们只需将他们的 zip 文件直接拖入浏览器,它就会让他们下载其中的所有文件。他们还可以通过拖入单个文件来创建新的 zip 文件。
I know it'd be better to do it serverside, but this project is just for a bit of fun.
我知道最好在服务器端进行,但这个项目只是为了好玩。
Dragging files into the browser should be easy enough if I take advantage of the various methods available. (Gmail style)
如果我利用各种可用的方法,将文件拖入浏览器应该很容易。(Gmail 风格)
Encoding/decoding should hopefully be fine. I've seen some as3 zip libraries so I'm sure I should be fine with that.
编码/解码应该没问题。我看过一些 as3 zip 库,所以我相信我应该没问题。
My issue is downloading the files at the end.
我的问题是最后下载文件。
window.location = 'data:jpg/image;base64,/9j/4AAQSkZJR....'
this works fine in firefox but not in chrome.
这在 Firefox 中工作正常,但在 chrome 中无效。
I can embed the files as images just fine in chrome using <img src="data:jpg/image;ba.." />
, but the files won't necessarily be images. They could be any format.
我可以使用 将文件作为图像嵌入到 chrome 中<img src="data:jpg/image;ba.." />
,但文件不一定是图像。它们可以是任何格式。
Can anyone think of another solution or some kind of workaround?
谁能想到另一种解决方案或某种解决方法?
采纳答案by Pekka
Ideas:
想法:
Try a
<a href="data:...." target="_blank">
(Untested)Use downloadifyinstead of data URLs (would work for IE as well)
尝试
<a href="data:...." target="_blank">
(未经测试)使用downloadify而不是数据 URL(也适用于 IE)
回答by owencm
If you also want to give a suggested name to the file (instead of the default 'download') you can use the following in Chrome, Firefox and some IE versions:
如果您还想为文件提供建议的名称(而不是默认的“下载”),您可以在 Chrome、Firefox 和某些 IE 版本中使用以下内容:
function downloadURI(uri, name) {
var link = document.createElement("a");
link.download = name;
link.href = uri;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
delete link;
}
And the following example shows it's use:
以下示例显示了它的用途:
downloadURI("data:text/html,HelloWorld!", "helloWorld.txt");
回答by Zibri
function download(dataurl, filename) {
var a = document.createElement("a");
a.href = dataurl;
a.setAttribute("download", filename);
a.click();
}
download("data:text/html,HelloWorld!", "helloWorld.txt");
or:
或者:
function download(url, filename) {
fetch(url).then(function(t) {
return t.blob().then((b)=>{
var a = document.createElement("a");
a.href = URL.createObjectURL(b);
a.setAttribute("download", filename);
a.click();
}
);
});
}
download("https://get.geojs.io/v1/ip/geo.json","geoip.json")
download("data:text/html,HelloWorld!", "helloWorld.txt");
回答by Martino Dino
Want to share my experience and help someone stuck on the downloads not working in Firefox and updated answer to 2014. The below snippet will work in both firefox and chrome and it will accept a filename:
想分享我的经验并帮助那些在 Firefox 中无法正常下载的人,并更新了 2014 年的答案。以下代码段在 Firefox 和 chrome 中都可以使用,并且可以接受文件名:
// Construct the <a> element
var link = document.createElement("a");
link.download = thefilename;
// Construct the uri
var uri = 'data:text/csv;charset=utf-8;base64,' + someb64data
link.href = uri;
document.body.appendChild(link);
link.click();
// Cleanup the DOM
document.body.removeChild(link);
回答by Jesus M C
Here is a pure JavaScript solution I tested working in Firefox and Chrome but not in Internet Explorer:
这是我在 Firefox 和 Chrome 但不在 Internet Explorer 中测试的纯 JavaScript 解决方案:
function downloadDataUrlFromJavascript(filename, dataUrl) {
// Construct the 'a' element
var link = document.createElement("a");
link.download = filename;
link.target = "_blank";
// Construct the URI
link.href = dataUrl;
document.body.appendChild(link);
link.click();
// Cleanup the DOM
document.body.removeChild(link);
delete link;
}
Cross-browser solutions found up until now:
迄今为止发现的跨浏览器解决方案:
downloadify -> Requires Flash
下载 -> 需要 Flash
databounce -> Tested in IE 10 and 11, and doesn't work for me. Requires a servlet and some customization. (Incorrectly detects navigator. I had to set IE in compatibility mode to test, default charset in servlet, JavaScript options object with correct servlet path for absolute paths...) For non-IE browsers, it opens the file in the same window.
databounce -> 在 IE 10 和 11 中测试过,对我不起作用。需要一个 servlet 和一些自定义。(错误地检测到导航器。我必须在兼容模式下设置 IE 进行测试,servlet 中的默认字符集,JavaScript 选项对象具有正确的 servlet 绝对路径路径......)对于非 IE 浏览器,它会在同一窗口中打开文件。
download.js -> http://danml.com/download.htmlAnother library similar but not tested. Claims to be pure JavaScript, not requiring servlet nor Flash, but doesn't work on IE <= 9.
download.js -> http://danml.com/download.html另一个类似但未测试的库。声称是纯 JavaScript,不需要 servlet 或 Flash,但不适用于 IE <= 9。
回答by Viacheslav Dobromyslov
There are several solutions but they depend on HTML5 and haven't been implemented completely in some browsers yet. Examples below were tested in Chrome and Firefox (partly works).
有几种解决方案,但它们依赖于 HTML5,并且尚未在某些浏览器中完全实现。下面的示例在 Chrome 和 Firefox 中进行了测试(部分有效)。
- Canvas examplewith save to file support. Just set your
document.location.href
to the data URI. - Anchor download example. It uses
<a href="your-data-uri" download="filename.txt">
to specify file name.
回答by kevinarpe
Combining answers from @owencm and @Chazt3n, this function will allow download of text from IE11, Firefox, and Chrome. (Sorry, I don't have access to Safari or Opera, but please add a comment if you try and it works.)
结合@owencm 和@Chazt3n 的回答,此功能将允许从 IE11、Firefox 和 Chrome 下载文本。(抱歉,我无权访问 Safari 或 Opera,但如果您尝试并成功,请添加评论。)
initiate_user_download = function(file_name, mime_type, text) {
// Anything but IE works here
if (undefined === window.navigator.msSaveOrOpenBlob) {
var e = document.createElement('a');
var href = 'data:' + mime_type + ';charset=utf-8,' + encodeURIComponent(text);
e.setAttribute('href', href);
e.setAttribute('download', file_name);
document.body.appendChild(e);
e.click();
document.body.removeChild(e);
}
// IE-specific code
else {
var charCodeArr = new Array(text.length);
for (var i = 0; i < text.length; ++i) {
var charCode = text.charCodeAt(i);
charCodeArr[i] = charCode;
}
var blob = new Blob([new Uint8Array(charCodeArr)], {type: mime_type});
window.navigator.msSaveOrOpenBlob(blob, file_name);
}
}
// Example:
initiate_user_download('data.csv', 'text/csv', 'Sample,Data,Here\n1,2,3\n');
回答by Chazt3n
For anyone having issues in IE:
对于在 IE 中遇到问题的任何人:
Please upvote the answer here by Yetti: saving canvas locally in IE
请为 Yetti 的答案点赞: 在 IE 中本地保存画布
dataURItoBlob = function(dataURI) {
var binary = atob(dataURI.split(',')[1]);
var array = [];
for(var i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i));
}
return new Blob([new Uint8Array(array)], {type: 'image/png'});
}
var blob = dataURItoBlob(uri);
window.navigator.msSaveOrOpenBlob(blob, "my-image.png");
回答by Piskvor left the building
Your problem essentially boils down to "not all browsers will support this".
您的问题基本上归结为“并非所有浏览器都支持这一点”。
You could try a workaround and serve the unzipped files from a Flash object, but then you'd lose the JS-only purity (anyway, I'm not sure whether you currently can "drag files into browser" without some sort of Flash workaround - is that a HTML5 feature maybe?)
您可以尝试一种解决方法并从 Flash 对象中提供解压缩的文件,但是您将失去纯 JS 的纯度(无论如何,我不确定您目前是否可以在没有某种 Flash 解决方法的情况下“将文件拖入浏览器” - 这可能是 HTML5 功能吗?)