问题
I want to move data generated in javascript to a file
I am using
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();
}
based on code from Is it possible to write data to file using only JavaScript?
The problem is that a 0xc2 is inserted before every character with ascii value above 0x79.
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
This happened in both firefox & chromium browsers in Ubuntu Linux. I'm hoping that some other blob type besides 'text/plain' will not have this behavior, but I'm having trouble finding the relevant documentation.
Dustin Soodak
Note: this is a new approach to question Can you make a textarea which doesn't automatically edit your text? which seems to be impossible
回答1:
I added 'application/octet-binary' to my google search and found an answer at "Create binary blob in JS". It looks like if you initialize the blob from a Uint8Array instead of a string, it no longer alters the data. Here is the full working code:
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();
}
来源:https://stackoverflow.com/questions/40477286/keep-javascript-blob-from-editing-data-when-saving-file