gpt4 book ai didi

javascript - 保存文件时阻止 javascript blob 编辑数据

转载 作者:太空宇宙 更新时间:2023-11-04 16:22:37 26 4
gpt4 key购买 nike

我想将 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

这发生在 Ubuntu Linux 中的 firefox 和 chromium 浏览器中。我希望除了“text/plain”之外的其他一些 blob 类型不会有这种行为,但我找不到相关文档。

达斯汀·苏达克

注意:这是一种新的提问方式 Can you make a textarea which doesn't automatically edit your text?这似乎是不可能的

最佳答案

我在 Google 搜索中添加了“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();
}

关于javascript - 保存文件时阻止 javascript blob 编辑数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40477286/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com