是否可以在LocalStorage中保存File对象,然后在用户返回页面时通过FileReader重新加载文件?

时间:2011-05-28 00:19:43

标签: javascript file html5 filereader

例如,假设用户将一些非常大的图像或媒体文件加载到您的Web应用程序中。当他们返回时,您希望您的应用程序显示他们之前加载的内容,但无法将实际文件数据保留在LocalStorage中,因为数据太大。

3 个答案:

答案 0 :(得分:4)

localStorage可能。存储在localStorage中的数据需要是可序列化的基本类型之一。这不包括File对象。

例如,这将按预期工作:

var el = document.createElement('input');
el.type='file';
el.onchange = function(e) {
  localStorage.file = JSON.stringify(this.files[0]);
  // LATER ON...
  var reader = new FileReader();
  reader.onload = function(e) {
    var result = this.result; // never reaches here.
  };
  reader.readAsText(JSON.parse(localStorage.f));
};
document.body.appendChild(el);

解决方案是使用更强大的存储选项,例如将文件内容写入HTML5 Filesystem或将其存储在IndexedDB中。

答案 1 :(得分:-1)

从技术上讲,如果您只需要在localStorage中保存小文件,就可以。

只是base64,因为它是一个字符串...它的localStorage友好。

我认为localStorage有~5MB的限制。 base64字符串的文件大小相当低,因此这是存储小图像的可行方法。如果你使用这种懒惰的方式,那么缺点是你必须要考虑5MB的限制。我认为这可能是一个解决方案,取决于您的需求。

答案 2 :(得分:-2)

是的,这是可能的。您可以将有关所需文件的任何信息插入LocalStorage,只要将其序列化为支持的基本类型之一即可。您也可以将整个文件序列化为LocalStorage并在以后检索,但是根据浏览器的不同,文件大小也有限制。

以下说明如何使用两种不同的方法实现这一目标:

(function () {
// localStorage with image
var storageFiles = JSON.parse(localStorage.getItem("storageFiles")) || {},
    elephant = document.getElementById("elephant"),
    storageFilesDate = storageFiles.date,
    date = new Date(),
    todaysDate = (date.getMonth() + 1).toString() + date.getDate().toString();

// Compare date and create localStorage if it's not existing/too old   
if (typeof storageFilesDate === "undefined" || storageFilesDate < todaysDate) {
    // Take action when the image has loaded
    elephant.addEventListener("load", function () {
        var imgCanvas = document.createElement("canvas"),
            imgContext = imgCanvas.getContext("2d");

        // Make sure canvas is as big as the picture
        imgCanvas.width = elephant.width;
        imgCanvas.height = elephant.height;

        // Draw image into canvas element
        imgContext.drawImage(elephant, 0, 0, elephant.width, elephant.height);

        // Save image as a data URL
        storageFiles.elephant = imgCanvas.toDataURL("image/png");

        // Set date for localStorage
        storageFiles.date = todaysDate;

        // Save as JSON in localStorage
        try {
            localStorage.setItem("storageFiles", JSON.stringify(storageFiles));
        }
        catch (e) {
                console.log("Storage failed: " + e);                
        }
    }, false);

    // Set initial image src    
    elephant.setAttribute("src", "elephant.png");
}
else {
    // Use image from localStorage
    elephant.setAttribute("src", storageFiles.elephant);
}

// Getting a file through XMLHttpRequest as an arraybuffer and creating a Blob
var rhinoStorage = localStorage.getItem("rhino"),
    rhino = document.getElementById("rhino");
if (rhinoStorage) {
    // Reuse existing Data URL from localStorage
    rhino.setAttribute("src", rhinoStorage);
}
else {
    // Create XHR, BlobBuilder and FileReader objects
    var xhr = new XMLHttpRequest(),
        blob,
        fileReader = new FileReader();

    xhr.open("GET", "rhino.png", true);
    // Set the responseType to arraybuffer. "blob" is an option too, rendering BlobBuilder unnecessary, but the support for "blob" is not widespread enough yet
    xhr.responseType = "arraybuffer";

    xhr.addEventListener("load", function () {
        if (xhr.status === 200) {
            // Create a blob from the response
            blob = new Blob([xhr.response], {type: "image/png"});

            // onload needed since Google Chrome doesn't support addEventListener for FileReader
            fileReader.onload = function (evt) {
                // Read out file contents as a Data URL
                var result = evt.target.result;
                // Set image src to Data URL
                rhino.setAttribute("src", result);
                // Store Data URL in localStorage
                try {
                    localStorage.setItem("rhino", result);
                }
                catch (e) {
                    console.log("Storage failed: " + e);
                }
            };
            // Load blob as Data URL
            fileReader.readAsDataURL(blob);
        }
    }, false);
    // Send XHR
    xhr.send();
}
})();

Source