如何将图像保存为HTML5文件系统的图像的URL [英] How to save a image to HTML5 filesystem with the url of image

查看:79
本文介绍了如何将图像保存为HTML5文件系统的图像的URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用HTML5系统来存储我的网站的图像,我发现有很多例子显示如何将本地图像存储到您的铬文件系统,但我找不到方法来获取图像然后将它存储在HTML5文件系统中。

这是我的代码,但它是错误的。



<$ p (xhr,data){
if(xhr.status == 200){
fs.root.getFile(test (fileWriter){$ b $}创建一个FileWriter对象FileEntry(log.txt)
fileEntry.createWriter(fileWriter){
fileWriter.onwriteend = function(e){
console.log('Write completed。');
};

fileWriter.onerror = function(e){
console.log('Write failed:'+ e.toString());
};
//创建一个新的Blob并将其写入log.txt。
var bb = new BlobBuilder(); //注意:Chrome 12中的window.WebKitBlobBuilder。
bb.append(data);
fileWriter.write(bb.getBlob('image / jpeg'));
回拨&&回调( test.jpg放在);
},errorHandler);

},errorHandler);
}
});


解决方案

这里是我使用的函数。
它使用Blob的构造函数,所以它可以在最新的Chrome上运行(这个版本没有废弃的BlobBuilder),而且在老的iOS 6上也没有xhr.responseType的blob。

<在注释中,您还会看到不赞成使用的BlobBuilder的代码。


注意:您使用的是XHR,所以必须启用CORS!

$ p $ window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
window.requestFileSystem(window.PERSISTENT,2 * 1024 * 1024,onFileSystemSuccess,失败);


函数onFileSystemSuccess(fileSystem){
fs = fileSystem;
console.log('文件系统初始化');

saveAsset('http://www.example-site-with-cors.com/test.png');


$ b函数saveAsset(url,callback,failCallback){
var filename = url.substring(url.lastIndexOf('/')+ 1);

//设置未定义的回调
if(!callback){
callback = function(cached_url){
console.log('download ok:'+ cached_url);
}; $!
$ b $ if(!failCallback){
failCallback = function(){
console.log('download failed');
};


//设置lookupTable如果没有定义
if(!window.lookupTable)
window.lookupTable = {};

// BlobBuilder shim
// var BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;

var xhr = new XMLHttpRequest();
xhr.open('GET',url,true);
// xhr.responseType ='blob';
xhr.responseType ='arraybuffer';

xhr.addEventListener('load',function(){

fs.root.getFile(filename,{create:true,exclusive:false},function(fileEntry) {
fileEntry.createWriter(function(writer){

writer.onwrite = function(e){
//将该文件保存到URL查找表的路径中
lookupTable [filename] = fileEntry.toURL();
callback(fileEntry.toURL());
};

writer.onerror = failCallback;

// var bb = new BlobBuilder();
var blob = new Blob([xhr.response],{type:''});
// bb.append(xhr。响应);
writer.write(blob);
// writer.write(bb.getBlob());
$ b $,failCallback);
}, failCallback);
});

xhr.addEventListener('error',failCallback);
xhr.send();

返回文件名;




function fail(evt){
console.log(evt.target.error.code);
}


I am trying to use HTML5 system to store images of my website, and I find there are many example to show how to store a local image to your chrome file system but I can't find the way to get a image by web url and then store it in HTML5 file system.

This is my code, but it's wrong.

        lib.ajax.get(file , function(xhr, data){
            if(xhr.status == 200){
                fs.root.getFile("test.jpg", {create: true}, function(fileEntry) {
                    // Create a FileWriter object for our FileEntry (log.txt).
                    fileEntry.createWriter(function(fileWriter) {
                        fileWriter.onwriteend = function(e) {
                            console.log('Write completed.');
                        };

                        fileWriter.onerror = function(e) {
                            console.log('Write failed: ' + e.toString());
                        };
                        // Create a new Blob and write it to log.txt.
                        var bb = new BlobBuilder(); // Note: window.WebKitBlobBuilder in Chrome 12.
                        bb.append(data);
                        fileWriter.write(bb.getBlob('image/jpeg'));
                        callback && callback("test.jpg");
                    }, errorHandler);

                }, errorHandler);
            }
        });

解决方案

Here the function I use. It use Blob constructor so it works on latest Chrome (thats lacks deprecated BlobBuilder) and works also on old iOS 6 that lacks 'blob' for xhr.responseType.

In comments you also see code for the deprecated BlobBuilder.

Notice: you are using XHR so CORS must be enabled!

window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
window.requestFileSystem(window.PERSISTENT, 2*1024*1024, onFileSystemSuccess, fail);


function onFileSystemSuccess(fileSystem) {
    fs = fileSystem;
    console.log('File system initialized');

    saveAsset('http://www.example-site-with-cors.com/test.png');
}


function saveAsset(url, callback, failCallback) {
    var filename = url.substring(url.lastIndexOf('/')+1);

    // Set callback when not defined
    if (!callback) {
        callback = function(cached_url) {
            console.log('download ok: ' + cached_url);
        };
    }
    if (!failCallback) {
        failCallback = function() {
            console.log('download failed');
        };
    }

    // Set lookupTable if not defined
    if (!window.lookupTable)
        window.lookupTable = {};

    // BlobBuilder shim
    // var BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;

    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    // xhr.responseType = 'blob';
    xhr.responseType = 'arraybuffer';

    xhr.addEventListener('load', function() {

        fs.root.getFile(filename, {create: true, exclusive: false}, function(fileEntry) {
            fileEntry.createWriter(function(writer) {

                writer.onwrite = function(e) {
                    // Save this file in the path to URL lookup table.
                    lookupTable[filename] = fileEntry.toURL();
                    callback(fileEntry.toURL());
                };

                writer.onerror = failCallback;

                // var bb = new BlobBuilder();
                var blob = new Blob([xhr.response], {type: ''});
                // bb.append(xhr.response);
                writer.write(blob);
                // writer.write(bb.getBlob());

            }, failCallback);
        }, failCallback);
    });

    xhr.addEventListener('error', failCallback);
    xhr.send();

    return filename;
}



function fail(evt) {
    console.log(evt.target.error.code);
}

这篇关于如何将图像保存为HTML5文件系统的图像的URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆