【问题标题】:Storing/Retrieving html 5 File object for resuming a broken file upload存储/检索 html 5 文件对象以恢复损坏的文件上传
【发布时间】:2013-11-22 20:30:00
【问题描述】:
我正在尝试使用 javascript 和 HTML 5 构建文件上传浏览器客户端。从网页中的文件输入表单(输入类型“文件”),浏览器提供带有 html 5 文件对象 (http://www.w3.org/TR/FileAPI/) 的文件句柄。使用此文件对象完成上传。但如果上传未完成,我希望恢复文件上传。因为,这个工作我在尝试恢复上传时需要 File 对象。 cookies 和 html 5 localstorage 只存储原始数据类型而不是对象。有没有办法存储/检索文件对象,或者从对象中提取实际的文件句柄,存储它并使用其构造函数生成文件对象。
服务器会维护上传状态,客户端只需要存储和检索这个文件对象。对客户端代码有任何建议/解决方法吗?
【问题讨论】:
标签:
javascript
html
file-upload
cookies
local-storage
【解决方案2】:
在 indexedDB 中存储文件很容易。 indexedDB 对于大型数据库等很有用,但即使您只是放入一个文件,它仍然可以工作。我知道@Gaurav 说了一些关于 indexedDB 的事情,但我会给你一个如何存储它的例子:
var indexedDB=window.indexedDB||window.webkitIndexedDB||window.mozIndexedDB;
function storeFile(fileObj,callback){
var openReq=indexedDB.open('upload-resume',1);
openReq.onerror=function(e){
console.error(e);
}
openReq.onupgradeneeded=function(e){
var db=openReq.result;
db.createObjectStore('upload-resume-store',{keyPath:'blah'});
}
openReq.onsuccess=function(e){
var db=openReq.result;
var req=db.transaction(['upload-resume-store'],'readwrite').objectStore('upload-resume-store').add({blah:'main',file:fileObj});
req.onerror=function(e){
console.error(e);
}
req.onsuccess=function(e){callback();}
}
}
function getFile(callback){
var openReq=indexedDB.open('upload-resume',1);
openReq.onerror=function(e){
console.error(e);
}
openReq.onupgradeneeded=function(e){
//this should have already been called before...so if this is here that means that the file was never stored
openReq.onsuccess=null;
callback(false);
}
openReq.onsuccess=function(e){
var req=db.transaction(['upload-resume-store'],'readonly').objectStore('upload-resume-store').get('blah');
req.onerror=function(e){
console.error(e);
}
req.onsuccess=function(e){
callback(req.result);
}
}
}
我之前遇到过 indexedDB 的问题,如果它不能正常工作,请告诉我。