2013-12-17 25 views
0

我正在寫一個函數,它從表單的文件輸入中獲取圖像,並使我能夠將其存儲在localstorage中。我寫的函數來實現這一目標:本地存儲功能中的圖像不起作用

function getImage() { 
    var pic = document.getElementById("image").files[0]; 
    var imgUrl; 
    var reader = new FileReader(); 
    reader.onload = function(e) { 
     var imgURL = reader.result; 
     saveDataToLocalStorage(imgURL); 
     return imgUrl; 
    } 
} 

然後在另一個函數我調用這個函數,並創建中,我存儲從其他形式的輸入,包括圖像值的JSON條目。它看起來像這樣:

var imgUrl = getImage(); 

    // Create new JSON entry 
    var json_entry = {'title': titleField.val(), 
         'image': imgUrl, 
         'content': contentField.val(), 
         'location': location}; 

可悲的imgUrl值是不確定的。有沒有控制檯錯誤。我究竟做錯了什麼?我該如何解決這個問題?

+1

看起來你試圖將二進制數據存儲在localStorage中,它不支持二進制數據? – adeneo

+0

你知道如何解決它嗎? – aardnoot

+0

我不知道如何解決它。以上代碼基於此示例:http://jsfiddle.net/VXdkC/2/ – aardnoot

回答

1

我真的不知道很多有關FileReader對象,但我可以從你的JS一眼(至少)有一件事是關閉的,請參閱:

var imgUrl = getImage(); 

getImage函數不返回任何事情;所以imgUrl肯定會是undefined以上。

如果你想要做的事與你FileReaderresult屬性,那麼你需要做這樣瓦特/一個回調,因爲你處理(異步)onload事件:

function getImage(callback) { 
    // What are you doing with this? 
    var pic = document.getElementById("image").files[0]; 

    var reader = new FileReader(); 
    reader.onload = function(e) { 
     var imgURL = reader.result; 
     saveDataToLocalStorage(imgURL); 

     // Note the difference here: rather than return from the event handler 
     // (which effectively does nothing) we pass the result to a callback. 
     callback(imgUrl); 
    } 

    // I assume you actually need to load something with the FileReader? 
} 

然後:

getImage(function(imgUrl) { 
    var json_entry = { 
     'title': titleField.val(), 
     'image': imgUrl, 
     'content': contentField.val(), 
     'location': location 
    }; 
}); 
0

它看起來像你忘記將讀者設置爲readAsDataUrl。可能的價值是作爲undefined回來,因爲localStorage本質上不知道如何序列化二進制數據。將讀取器設置爲readAsDataUrl更改爲reader.result

var reader = new FileReader(); 
reader.onload = function(e) { 
    var imgURL = reader.result; 
    saveDataToLocalStorage(imgURL); 
    callback(imgUrl); 
}; 
// add this line 
reader.readAsDataURL(pic); 

看一看this文章,題爲尤其是閱讀文件部分。請注意,在鏈接示例中,作者使用e.target.result而不是reader.result。這應該是相同的值。