2012-08-10 229 views
4

我嘗試使用HTML5系統來存儲我的網站上的圖像的URL,我覺得有很多例子來說明如何將本地圖像存儲到Chrome文件系統但我無法找到通過網址獲取圖像的方式,然後將其存儲在HTML5文件系統中。如何將圖像保存到HTML5文件系統與圖像

這是我的代碼,但它是錯誤的。

 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); 
      } 
     }); 

回答

1

我找到了一種方法來做到這一點。

使用canvans.toDataURL傳輸數據格式。

var img = new Image(); 
       var cvs = document.createElement('canvas'); 
       var ctx = cvs.getContext("2d"); 
       img.src = file; 
       img.onload = function(){ 
        cvs.width = img.width; 
        cvs.height = img.height; 
        ctx.drawImage(img, 0, 0); 
        var imd = cvs.toDataURL(contentType[extname]); 
        var ui8a = convertDataURIToBinary(imd); 
        var bb = new BlobBuilder(); 
        bb.append(ui8a.buffer); 
        fs.root.getFile(path, {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.'); 
           callback && callback("test.jpg"); 
          }; 

          fileWriter.onerror = function(e) { 
           console.log('Write failed: ' + e.toString()); 
          }; 

          fileWriter.write(bb.getBlob(contentType[extname])); 
         }); 
        }); 
       }; 



    function convertDataURIToBinary(dataURI) { 
    var BASE64_MARKER = ';base64,'; 
    var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length; 
    var base64 = dataURI.substring(base64Index); 
    var raw = window.atob(base64); 
    var rawLength = raw.length; 
    var array = new Uint8Array(new ArrayBuffer(rawLength)); 

    for (i = 0; i < rawLength; i++) { 
     array[i] = raw.charCodeAt(i); 
    } 
    return array; 
} 

我得到的幫助從這裏enter link description here

塊引用

2

的問題是,瀏覽器將解析XHR響應數據爲UTF-8, 所以問題是覆蓋Mime類型:

window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem; 

var xhr = new XMLHttpRequest(); 
var photoUrl = 'http://localhost:3000/image.jpg'; 
xhr.open('GET', photoUrl, true); 

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

function stringToBinary(response) { 
    var byteArray = new Uint8Array(response.length); 
    for (var i = 0; i < response.length; i++) { 
    byteArray[i] = response.charCodeAt(i) & 0xff; 
    } 
    return byteArray 
} 

function onInitFs(fs) { 
    xhr.onreadystatechange = function() { 
    if (xhr.readyState == 4 && xhr.status == 200) { 
     fs.root.getFile('image.jpg', {'create': true}, function(fileEntry) { 
     fileEntry.createWriter(function(fileWriter) { 
      fileWriter.onwriteend = function(event) { 
      $('body').append('<img src="' + fileEntry.toURL() + '"/>'); 
      } 

      buffer = stringToBinary(xhr.response); 
      var blob = new Blob([ buffer ], { type: 'image/jpeg' }) 

      fileWriter.write(blob); 
     }, errorHandler); 
     }); 
    } 
    } 
    xhr.send(); 
} 

var errorHandler = function(err) { 
    console.log(err); 
} 

$(function() { 
    webkitStorageInfo.requestQuota(PERSISTENT, 5*1024*1024, function(grantedBytes) { 
    requestFileSystem(PERSISTENT, grantedBytes, onInitFs, errorHandler) 
    }, errorHandler) 
}) 
2

這裏解釋我使用的功能。 它使用Blob的構造函數,因此它適用於最新的Chrome(即沒有棄用的BlobBuilder),也適用於缺少xhr.responseType的「blob」的舊iOS 6。

在評論,你也看到了已廢棄的BlobBuilder代碼。

注意:您正在使用XHR所以CORS必須啓用!

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); 
} 
+0

'window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;' – zenden2k 2015-09-07 15:17:21

1

的技巧是使用xhr.responseType = 'blob'

var fs = .... // your fileSystem 
function download(fs,url,file,win,fail) { 
    var xhr = new XMLHttpRequest(); 
    xhr.open('GET', url); 
    xhr.responseType = "blob"; 
    xhr.onreadystatechange = function() { 
    if (xhr.readyState == 4) { 
     if(xhr.status === 200){ 
     fs.root.getFile(file,{create:true},function(fileEntry){ 
      fileEntry.createWriter(function(writer){ 
      writer.onwriteend = win; 
      writer.onerror = fail; 
      writer.write(xhr.response); 
      }) 
     },fail) 
     } else { 
     fail(xhr.status); 
     } 
    } 
    }; 
    xhr.send(); 
    return xhr; 
}; 

基於cordova-promise-fs(披露:我是作者)

+0

太棒了!謝謝:) – 2016-11-24 14:03:47

相關問題