使用 Base64 编写 HTML5 二进制文件
如您所知,HTML 5 提供了一个很好的 FileAPI。我构建了一个系统,用户接收 Base64 编码的字符串,需要将其写入磁盘(具有适当的权限,因为它是 Google Chrome 应用程序)。我的代码如下:(稍微清除了不必要的东西)
function onInitFs(fs){
fs.root.getFile(fileName, {create: true}, function(fileEntry) {
fileEntry.createWriter(function(fileWriter) {
var bb = new window.WebKitBlobBuilder();
bb.append( atob(dataInBase64Format));
fileWriter.write(bb.getBlob());
}, errorHandler);
console.log( fileEntry.toURL());
}, errorHandler);
}
但是,我的原始文件大小是:6302446字节,服务器将它们作为Base64以8403264字节发送,但是保存的文件是9242715字节。当然,我知道出了问题,我查看了文件,它只是一个很好的字符串。没有出现华丽的人物。我假设我以文本模式编写,atob 只是将其转换为另一个字符串;我需要将其转换为二进制格式(也许是数组?)并强制我的 fileWriter 以二进制模式而不是文本模式写入。我在网上搜索过,但找不到解决方案。我在 StackOverflow 上发现了这个问题 Google Chrome Base64 方法能够处理来自文件 API 的二进制数据吗? 但这对我没有帮助。
如何将 Base64 字符串转换为正确的数据结构并让 fileWriter 写入它?
as you know HTML 5 offers a nice FileAPI. I have built a system where user recieves a Base64 encoded string, needs to be written on the disk (Has proper permissions, because it is a Google Chrome App). My code is the following: (a little cleared of unnecessary things)
function onInitFs(fs){
fs.root.getFile(fileName, {create: true}, function(fileEntry) {
fileEntry.createWriter(function(fileWriter) {
var bb = new window.WebKitBlobBuilder();
bb.append( atob(dataInBase64Format));
fileWriter.write(bb.getBlob());
}, errorHandler);
console.log( fileEntry.toURL());
}, errorHandler);
}
However, my original file size is: 6302446 bytes, and server sent them as Base64 in 8403264 bytes, however the saved file is 9242715 bytes. Of course I understood something is wrong and I looked the file and it is just a nice string. No fancy characters appears. I assume that I write in text mode and atob just converts it to another string; which I need to convert to binary format (in an array perhaps?) and force my fileWriter to write in binary mode, not text mode. I have searched the web, but could not find a solution. I have found this question on StackOverflow Are Google Chrome Base64 methods capable of handling binary data from the File API? but it did not help me.
How can I convert my Base64 string to proper data structure and have my fileWriter to write it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我编写了一个扩展,它使用 Chrome 捕获屏幕截图,将其放在画布上,调整其大小,然后使用文件系统 API 保存画布数据。不确定这是否与您的直接相似,但也许大部分代码就足够了?
在这种情况下,我假设我的
dataURI
(例如myCanvas.toDataURL("image/png")
)与您的dataInBase64Format
具有相同的 Base64 格式>。功能:
用途:
I wrote an extension that captures a screenshot using Chrome, puts it on a canvas, resizes it, then saves the canvas data using the Filesystem API. Not sure if this is directly similar to yours, but perhaps most of the code will suffice?
In this case, I assume my
dataURI
(egmyCanvas.toDataURL("image/png")
) would be the same Base64 format as yourdataInBase64Format
.Function:
Usage: