能够在另一个功能中访问本地存储图像

时间:2014-04-02 18:58:23

标签: javascript html5 local-storage

我试图创建一个应用程序,其中我有本地存储条目,其中包含一些图像信息。我有一个处理图像的文件的函数和一个在我的表单提交时创建我的条目的函数。现在我需要将图像传递给在提交表单时创建条目的函数。我怎么能这样做?

文件处理功能:

$('#image').on('change', handleFileSelect);

function handleFileSelect(e) {
    var photos = e.target.files;
    for (var i = 0; i < photos.length; i++) {
        var photo = photos[i];
        if (!photo.type.match('image.*')) {
            continue;
        }
        var reader = new FileReader();
        reader.onload = function(e) {
            var img = e.target.result;
            // I want my image to be in the json_entry I create in submitForm();
        }
        reader.readAsDataURL(photo);
    }
}

提交表单时的功能以及创建条目的位置:

function submitForm(event) {
    event.preventDefault();

    // Create new JSON entry
    var json_entry = {'title': $("#title").val(),
                        'image': // I want my image to be in here,
                        'content': $("#story").val(),
                        'location': $("#locatie").val(),
                        'location_lat': $("#locatie_lat").val(),
                        'location_lon': $("#locatie_lon").val(),
                        'date': getCurrentDate(),
                        'key': Math.round(new Date().getTime() / 1000)};

    //Put the entry in localstorage
    localStorage.setItem(Math.round(new Date().getTime() / 1000), JSON.stringify(json_entry));

    //Add the entry to the overview
    $('#overview').append('<article class="diary_item" rel="'+json_entry.key+'"><h2>'+json_entry.title+'</h2><div style="position:relative;"><img class="entry_img" src="'+json_entry.image+'"><div class="location"><img src="gfx/location.svg">&nbsp;&nbsp;'+json_entry.location+'</div><img class="delete" src="gfx/close.svg" /></div><p>'+json_entry.content+'<span class="time">Added on:&nbsp;'+json_entry.date+'</span></p></article>');

}

我希望我的问题很明确,有人可以帮助我。我真的无法让这件事发挥作用:(

1 个答案:

答案 0 :(得分:0)

您已经决定将图像传递并存储为数据uri字符串。

据我了解,问题是如何将该字符串转换为其他函数。那么这是一个非常简单的方法。只需将其存储在全局变量中即可。