gpt4 book ai didi

javascript - BlobBuilder 破坏二进制数据

转载 作者:太空狗 更新时间:2023-10-29 13:58:01 24 4
gpt4 key购买 nike

我对 BlobBuilder (Chrome11) 有疑问我尝试使用 XHR 请求从服务器获取图像。然后我尝试使用 BlobBuilder/FileWriter 将它保存到本地 FS。互联网上的每个示例都是关于使用文本/纯 MIME 类型的,这些示例工作正常。但是当我尝试写入使用 XHR 获得的二进制数据时,文件大小变得比原始文件大小大 1.5-2 倍。并且无法在 Picasa/Eye Of Gnome 中查看。

var xhr = new XMLHttpRequest();
var photoOrigUrl = 'http://www.google.ru/images/nav_logo72.png';
xhr.open('GET', photoOrigUrl, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var contentType = xhr.getResponseHeader('Content-type');

fsLink.root.getFile('nav_logo72.png', {'create': true}, function(fileEntry) {
fileEntry.createWriter(function(fileWriter) {
var BlobBuilderObj = new (window.BlobBuilder || window.WebKitBlobBuilder)();
BlobBuilderObj.append(xhr.responseText);

fileWriter.write(BlobBuilderObj.getBlob(contentType));
}, function(resultError) {
console.log('writing file to file system failed ( code ' + resultError.code + ')');
});
});
}
}

xhr.send();

fsLink 存在,这是扩展。

最佳答案

问题是 BlobBuilder.append(xhr.responseText) 将其参数检测为 UTF-8 字符串,这是 XHR 返回的内容,而不是二进制数据,这才是它真正的样子.有几个技巧可以让 BlobBuilder 将其读取为二进制数据而不是字符串数据:

var xhr = new XMLHttpRequest();
var photoOrigUrl = 'http://www.google.ru/images/nav_logo72.png';
xhr.open('GET', photoOrigUrl, true);

// CHANGE 1: This stops the browser from parsing the data as UTF-8:
xhr.overrideMimeType('text/plain; charset=x-user-defined');

xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var contentType = xhr.getResponseHeader('Content-type');

fsLink.root.getFile('nav_logo72.png', {'create': true}, function(fileEntry) {
fileEntry.createWriter(function(fileWriter) {

// CHANGE 2: convert string object into a binary object
var byteArray = new Uint8Array(xhr.response.length);
for (var i = 0; i < xhr.response.length; i++) {
byteArray[i] = xhr.response.charCodeAt(i) & 0xff;
}

var BlobBuilderObj = new (window.BlobBuilder || window.WebKitBlobBuilder)();

// CHANGE 3: Pass the BlobBuilder an ArrayBuffer instead of a string
BlobBuilderObj.append(byteArray.buffer);

// CHANGE 4: not sure if it's needed, but keep only the necessary
// part of the Internet Media Type string
fileWriter.write(BlobBuilderObj.getBlob(contentType.split(";")[0]));
}, function(resultError) {
console.log('writing file to file system failed ( code ' + resultError.code + ')');
});
});
}
}

xhr.send();

这给了我一个与 xhr.getResponseHeader('Content-Length') 建议的长度相同的文件。

关于javascript - BlobBuilder 破坏二进制数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6170421/

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