JavaScript:创建和保存文件 [英] JavaScript: Create and save file
问题描述
我有要写入文件的数据,并打开一个文件对话框供用户选择文件的保存位置.如果它适用于所有浏览器就好了,但它必须适用于 Chrome.我想在客户端完成这一切.
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.
如果有帮助的话,使用 HTML 也可以.
Using HTML is fine too, if that helps.
推荐答案
Awesomeness01 对代码的微小改进(不需要锚标记),按照 trueimage 的建议添加(支持 IE):
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);
}
}
经测试可在 Chrome、FireFox 和 IE10 中正常工作.
Tested to be working properly in Chrome, FireFox and IE10.
在 Safari 中,数据会在新选项卡中打开,您必须手动保存此文件.
In Safari, the data gets opened in a new tab and one would have to manually save this file.
这篇关于JavaScript:创建和保存文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!