【发布时间】:2018-06-13 10:53:54
【问题描述】:
我的应用是科尔多瓦应用。我尝试为平台浏览器执行以下操作。我知道所描述的问题不会在真实设备平台上发生。
我尝试执行以下操作:
- 通过 XMLHttpRequest 下载图片文件
- 使用 XMLHttpRequest 响应中的 blob 通过 createObjectURL 显示图像
- 将文件写入本地文件系统(使用 cordova-plugin-file 使 fileSystem API 在 Firefox 中可用)
- 使用本地文件系统中文件的 blob 通过 createObjectURL 显示图像
我可以从保存的文件中创建一个 blob,但之后图像就损坏了。
这是代码:
var filesystem;
var downloaddir;
var filename = 'e44498f0b0964152632bd0c82342914b859c543e.jpeg'
var downloadurl = 'http://adomain.com/public/content_images/'+filename;
function download(){
filesystem.root.getFile(
'/ressources/'+filename,
{ create: true, exclusive: false },
function (fileEntry) {
var oReq = new XMLHttpRequest();
oReq.open("GET", downloadurl, true);
oReq.responseType = "blob";
oReq.onload = function (oEvent) {
var blob = oReq.response;
if (blob) {
fileEntry.createWriter(function (fileWriter) {
fileWriter.onwriteend = function (e) {
console.log(fileEntry.toURL());// Works in Chrome and Firefox, but file URIs cannot be used for security reasons. So image is not displayed if this RUL is used in image src attribute
console.log(window.URL.createObjectURL(blob));// work in chrome and firefox. This is what I like to have in the end but using a file.
// Now I want to use the file and transform it in a objectURL, this is where I struggle
fileEntry.file(function(file){
console.log(window.URL.createObjectURL(file));// works in chrome bot not in firefox. Firefox says :"TypeError: Argument 1 is not valid for any of the 1-argument overloads of URL.createObjectURL."
var readerBlob = new FileReader();
readerBlob.onload = function(event){
var blob = new Blob([event.target.result], {type: 'image/jpg'});
console.log(window.URL.createObjectURL(blob));// blob uri will be created, but image is broken. Here I want to have a working objectURL that work for Chrome and Firefox
};
readerBlob.readAsBinaryString(file);
});
};
fileWriter.onerror = function (e) {
};
fileWriter.write(blob);
});
} else console.error('we didnt get an XHR response!');
};
oReq.send(null);
},
function (error) {
console.log('error creating file');
console.log(error);
}
);
}
document.addEventListener("deviceready", function(){
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
window.requestFileSystem(window.TEMPORARY, 10 * 1024*1024, function (fs) {
filesystem = fs;
filesystem.root.getDirectory(
'/ressources/',
{create:true},
function(dirEntry){
console.log('download dir created');
downloaddir = dirEntry;
download();
},
function(error){
}
);
});
}, false);
【问题讨论】:
-
尝试书写和阅读任何其他内容,例如测试字符串。是不是也被破坏了?
-
是的,我可以使用“Lorem ipsum”和 mimetype text/plain 创建一个 blob。然后我将它写入文件系统,使用 readAsText 读取文件并得到“Lorem ipsum”作为结果。在 Firefox 中像魅力一样工作。 Chrome 给了我的“Lorem ipsum”加上一个看起来像图像数据的大字符串。删除文件并重试后,我在 Chrome 中也得到了“Lorem ipsum”。在创建之前删除图像文件可能是个好主意。我试试看。
-
我可以将文件读取为 DataURL。这适用于 Firefox,并且图像显示正确。所以图像文件存储正确。
标签: javascript cordova filesystems blob