是否有可能在LocalStorage中保存File对象,然后当用户回到页面时通过FileReader重新加载File? [英] Is it possible to save a File object in LocalStorage and then reload a File via FileReader when a user comes back to a page?

查看:199
本文介绍了是否有可能在LocalStorage中保存File对象,然后当用户回到页面时通过FileReader重新加载File?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,假设用户将一些非常大的图片或媒体文件加载到您的网络应用程序中。当他们返回时,您希望应用程序显示以前加载的内容,但无法将实际文件数据保留在LocalStorage中,因为数据太大。 >。存储在 localStorage 中的数据需要是可序列化的基本类型之一。这不包括 File 对象。 例如,这将不是工作正如你所期待的那样:

pre $ 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; //永远不会到达这里
};
reader.readAsText(JSON.parse(localStorage.f));
};
document.body.appendChild(el);

解决方法是使用更强大的存储选项,如将文件内容写入 HTML5文件系统或将其存储在 IndexedDB


For example, say the user loads some very large images or media files in to your web app. When they return you want your app to show what they've previously loaded, but can't keep the actual file data in LocalStorage because the data is too large.

解决方案

This is NOT possible with localStorage. Data stored in localStorage needs to be one of the primitive types that can be serializable. This does not include the File object.

For example, this will not work as you'd expect:

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

The solution is to use a more powerful storage option like writing the file contents to the HTML5 Filesystem or stashing it in IndexedDB.

这篇关于是否有可能在LocalStorage中保存File对象,然后当用户回到页面时通过FileReader重新加载File?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆