[英]Saving a Uint8Array to a binary file
I am working on a web app that opens binary files and allows them to be edited.我正在开发一个可以打开二进制文件并允许对其进行编辑的 Web 应用程序。
This process is basically ondrop -> dataTransfer.files[0] -> FileReader -> Uint8Array
这个过程基本上就是
ondrop -> dataTransfer.files[0] -> FileReader -> Uint8Array
Essentially, I want to be able to save the modified file back as a binary file.本质上,我希望能够将修改后的文件保存回二进制文件。 Ideally as a file download with a specified file name.
理想情况下,作为具有指定文件名的文件下载。
There doesn't seem to be any standard method of doing this, and that sucks, because everything up to that point is well supported.似乎没有任何标准方法可以做到这一点,这很糟糕,因为到目前为止的一切都得到了很好的支持。
I am currently converting the array to a string using String.fromCharCode()
, base64 encoding that, and using a data uri in a hyperlink like data:application/octet-stream;base64,..
, along with the download
attribute to specify filename.我目前正在使用
String.fromCharCode()
将数组转换为字符串,base64 编码,并在像data:application/octet-stream;base64,..
这样的超链接中使用数据 uri 以及用于指定文件名的download
属性.
It seems to work, but it's quite hacky and I think converting the raw bytes to a string might introduce encoding issues depending on the byte values.它似乎有效,但它很hacky,我认为将原始字节转换为字符串可能会根据字节值引入编码问题。 I don't want the data to become corrupt or break the string.
我不希望数据损坏或破坏字符串。
Barring that, is there a better/proper method for getting an array of bytes as a binary file to the user?除此之外,是否有更好/正确的方法将字节数组作为二进制文件提供给用户?
These are utilities that I use to download files cross-browser.这些是我用来跨浏览器下载文件的实用程序。 The nifty thing about this is that you can actually set the
download
property of a link to the name you want your filename to be.这样做的妙处在于,您实际上可以将链接的
download
属性设置为您希望文件名的名称。
FYI the mimeType for binary is application/octet-stream
仅供参考,二进制的 mimeType 是
application/octet-stream
var downloadBlob, downloadURL;
downloadBlob = function(data, fileName, mimeType) {
var blob, url;
blob = new Blob([data], {
type: mimeType
});
url = window.URL.createObjectURL(blob);
downloadURL(url, fileName);
setTimeout(function() {
return window.URL.revokeObjectURL(url);
}, 1000);
};
downloadURL = function(data, fileName) {
var a;
a = document.createElement('a');
a.href = data;
a.download = fileName;
document.body.appendChild(a);
a.style = 'display: none';
a.click();
a.remove();
};
Usage:用法:
downloadBlob(myBinaryBlob, 'some-file.bin', 'application/octet-stream');
(shorter) ES6 version of the top answer: (较短)ES6 版本的最佳答案:
const downloadURL = (data, fileName) => {
const a = document.createElement('a')
a.href = data
a.download = fileName
document.body.appendChild(a)
a.style.display = 'none'
a.click()
a.remove()
}
const downloadBlob = (data, fileName, mimeType) => {
const blob = new Blob([data], {
type: mimeType
})
const url = window.URL.createObjectURL(blob)
downloadURL(url, fileName)
setTimeout(() => window.URL.revokeObjectURL(url), 1000)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.