是否可以仅使用JavaScript将数据写入文件?我希望使用JavaScript将数据写入现有文件。我不想把它打印在控制台上。我想把数据写到abc.txt..我读了许多答案的问题,但每一个地方,他们都打印在控制台上。在某些地方,他们给出了代码,但它不起作用。因此,请任何人能帮助我如何实际写入数据到文件。我引用了代码,但它不起作用:它给出了错误: Uncaught TypeError: Illegal constructor铬和 SecurityError: The operation is insecure.论莫兹拉var f = "sometextfile.txt";writeTextFile(f, "Spoon")writeTextFile(f, "Cheese monkey")writeTextFile(f, "Onion")
function writeTextFile(afilename, output){
var txtFile =new File(afilename);
txtFile.writeln(output);
txtFile.close();}那么,我们真的可以只使用Javascript或不使用Javascript将数据写入文件吗?请提前帮我谢谢
3 回答
慕尼黑的夜晚无繁华
TA贡献1864条经验 获得超6个赞
如果您试图在客户端计算机上编写文件,则不能以任何跨浏览器的方式这样做。IE确实有允许“受信任的”应用程序使用ActiveX对象来读取/写入文件的方法。 如果您试图将其保存在您的服务器上,那么只需将文本数据传递给您的服务器,并使用某种服务器端语言执行文件编写代码。 要在客户端存储一些相当小的信息,可以选择cookie。 使用HTML 5 API进行本地存储。
温温酱
TA贡献1752条经验 获得超4个赞
BlobURL.createObjectURL
download
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);
// returns a URL you can use as a href
return textFile;
};textarea.
var create = document.getElementById('create'),
textbox = document.getElementById('textbox');
create.addEventListener('click', function () {
var link = document.createElement('a');
link.setAttribute('download', 'info.txt');
link.href = makeTextFile(textbox.value);
document.body.appendChild(link);
// wait for the link to be added to the document
window.requestAnimationFrame(function () {
var event = new MouseEvent('click');
link.dispatchEvent(event);
document.body.removeChild(link);
});
}, false);
神不在的星期二
TA贡献1963条经验 获得超6个赞
function download(strData, strFileName, strMimeType) {
var D = document,
A = arguments,
a = D.createElement("a"),
d = A[0],
n = A[1],
t = A[2] || "text/plain";
//build download link:
a.href = "data:" + strMimeType + "charset=utf-8," + escape(strData);
if (window.MSBlobBuilder) { // IE10
var bb = new MSBlobBuilder();
bb.append(strData);
return navigator.msSaveBlob(bb, strFileName);
} /* end if(window.MSBlobBuilder) */
if ('download' in a) { //FF20, CH19
a.setAttribute("download", n);
a.innerHTML = "downloading...";
D.body.appendChild(a);
setTimeout(function() {
var e = D.createEvent("MouseEvents");
e.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
a.dispatchEvent(e);
D.body.removeChild(a);
}, 66);
return true;
}; /* end if('download' in a) */
//do iframe dataURL download: (older W3)
var f = D.createElement("iframe");
D.body.appendChild(f);
f.src = "data:" + (A[2] ? A[2] : "application/octet-stream") + (window.btoa ? ";base64" : "") + ","
+ (window.btoa ? window.btoa : escape)(strData);
setTimeout(function() {
D.body.removeChild(f);
}, 333);
return true;}download('the content of the file', 'filename.txt', 'text/plain');
添加回答
举报
0/150
提交
取消
