2015-10-02 23 views
2

當我嘗試存儲一個blob(通過XMLHttpRequestGET請求檢索,Safari瀏覽器在iOS 8.4引發錯誤:嘗試存儲BLOB在iOS的Safari瀏覽器8投DataCloneError

DataCloneError: DOM IDBDatabase Exception 25: The data being stored could 
not be cloned by the internal structured cloning algorithm 

這正好與我的代碼,同時也下面這個例子:http://robnyman.github.io/html5demos/indexeddb/

這是導致我的代碼(和上面的例子)失敗行:

//This throws the error 
var put = transaction.objectStore("elephants").put(blob, "image"); 

是否有一個修復 爲了這? blob是否需要首先進行base64編碼(就像你必須使用WebSQL一樣)?

我的代碼(在桌面版Chrome/Firefox和Chrome/Firefox的Android上的作品):

var xhr = new XMLHttpRequest(); 
var blob; 

//Get the Video 
xhr.open("GET", "test.mp4", true); 

//Set as blob 
xhr.responseType = "blob"; 

//Listen for blob 
xhr.addEventListener("load", function() { 
     if (xhr.status === 200) { 
      blob = xhr.response; 

      //Start transaction 
      var transaction = db.transaction(["Videos"], "readwrite"); 

      //IT FAILS HERE 
      var put = transaction.objectStore("Videos").put(blob, "savedvideo"); 

     } 
     else { 
      console.log("ERROR: Unable to download video."); 
     } 
}, false); 

xhr.send(); 

回答

3

對於一些原因(這是一個bug),就像iOS的Safari瀏覽器7的的WebSQL ,你不能在iOS Safari 8的IndexedDB中存儲一個BLOB。你必須將它轉換爲base64,然後它將存儲沒有錯誤。 (我再說一遍,這是一個bug)

因此,更改代碼這樣:從XMLHttpRequest的

//We'll make an array of unsigned ints to convert 
var uInt8Array = new Uint8Array(xhr.response); 
var i = uInt8Array.length; 
var binaryString = new Array(i); 
while (i--) 
{ 
    //Convert each to character 
    binaryString[i] = String.fromCharCode(uInt8Array[i]); 
} 

//Make into a string 
var data = binaryString.join(''); 

//Use built in btoa to make it a base64 encoded string 
var base64 = window.btoa(data); 

//Now we can save it 
var transaction = db.transaction(["Videos"], "readwrite"); 
var put = transaction.objectStore("Videos").put(base64, "savedvideo"); 
取回後

變化響應類型

xhr.responseType = "arraybuffer"; 

在數據庫中存儲

從IndexedDB中獲取表格後,c反轉:

//Convert back to bytes 
var data = atob(event.target.result); 

//Make back into unsigned array 
var asArray = new Uint8Array(data.length); 

for(var i = 0, len = data.length; i < len; ++i) 
{ 
    //Get back as int 
    asArray[i] = data.charCodeAt(i);  
} 

//Make into a blob of proper type 
var blob = new Blob([ asArray.buffer ], {type: "video/mp4"}); 

//Make into object url for video source 
var videoURL = URL.createObjectURL(blob); 
+0

感謝您抽出時間將此記入此記錄。你遇到過任何其他應該鏈接到這裏的StackOverflow問題嗎?或者在其他StackExchange網站發佈問題? – sideshowbarker

+0

另外,你知道這是否有一個開放的Safari/WebKit https://bugs.webkit.org/錯誤?如果沒有,請考慮舉一個。不管(如果已經有一個開放的,或者如果你打開一個),也可以鏈接到這裏。 – sideshowbarker

+0

@sideshowbarker我確實在Apple的bug數據庫上創建了一個bug,而不是webkit,它不是一個WebKit問題(在關閉WebKit之前在Chrome中工作)這是Safari的實現,這是錯誤的。我發現其他一些老問題可能會遇到同樣的問題(不知道他們的代碼是不存在的),但沒有答案。 –

相關問題