是否有可能在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?
问题描述
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屋!