我想将javascript中生成的数据移动到文件
我正在使用
function saveTextAsFile(textToWrite,FileName){
var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});
var downloadLink = document.createElement("a");
downloadLink.download = FileName;
downloadLink.innerHTML = "Download File";
if (window.webkitURL != null){
// Chrome allows the link to be clicked
// without actually adding it to the DOM.
downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
}
else{
// Firefox requires the link to be added to the DOM
// before it can be clicked.
downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
}
downloadLink.click();
}
基于来自的代码 Is it possible to write data to file using only JavaScript?
问题是在ascii值高于0x79的每个字符之前插入0xc2。
000041e0 30 35 5d 22 57 69 72 65 6c 65 73 73 22 3d 30 0a |05]"Wireless"=0.|
000041f0 00 00 c2 b0 c2 a0 c2 80 7f |.........|
000041f9
这发生在firefox& Ubuntu Linux中的chrome浏览器。 我希望除了'text / plain'之外的其他一些blob类型不会有这种行为,但是我找不到相关的文档。
达斯汀苏达克注意:这是一种新的问题解决方法 Can you make a textarea which doesn't automatically edit your text? 这似乎是不可能的
答案 0 :(得分:1)
我在我的谷歌搜索中添加了'application / octet-binary'并找到了答案 “Create binary blob in JS”。 看起来如果从Uint8Array而不是字符串初始化blob,它就不再改变数据。以下是完整的工作代码:
function saveTextAsFile(textToWrite,FileName){
function destroyClickedElement(event){
document.body.removeChild(event.target);
}
var byteArray = new Uint8Array(textToWrite.length);
for (var i=0;i<byteArray.length;i++){
byteArray[i]=textToWrite.charCodeAt(i);
}
var textFileAsBlob = new Blob([byteArray], {type:'application/octet-binary'});
var downloadLink = document.createElement("a");
downloadLink.download = FileName;
downloadLink.innerHTML = "Download File";
if (window.webkitURL != null){
// Chrome allows the link to be clicked
// without actually adding it to the DOM.
downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
}
else{
// Firefox requires the link to be added to the DOM
// before it can be clicked.
downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
downloadLink.onclick = destroyClickedElement;
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
}
downloadLink.click();
}