存储/检索 html 5 文件对象,用于恢复损坏的文件上传

Storing/Retrieving html 5 File object for resuming a broken file upload

本文关键字:文件 恢复 损坏 用于 对象 检索 html 存储      更新时间:2023-09-26

我正在尝试使用javascript和HTML 5构建文件上传浏览器客户端。从网页中的文件输入表单(输入类型"file")中,浏览器提供带有html 5文件对象(http://www.w3.org/TR/FileAPI/)的文件句柄。上传是使用此文件对象完成的。但是,如果上传未完成,我希望恢复文件上传。为此,我需要在尝试恢复上传时随身携带 File 对象。Cookie 和 HTML 5 localStorage 仅存储原始数据类型,而不存储对象。有没有办法存储/检索文件对象,或者从对象中提取实际的文件句柄,存储它并使用其构造函数创建 File 对象。

服务器将维护上传状态,客户端唯一需要做的就是存储和检索此文件对象。对客户端代码有什么建议/解决方法吗?

存储在

locastorage中的数据必须是原始数据类型,您需要在将其保存在此处之前序列化任何数据。由于File对象不是原始数据类型之一,因此您无法将其保存到localstorage中。不要忘记,可以保存在localstorage中的最大数据数量有一个限制(5MB),cookies它甚至更少。因此使用上述选项是不可能的。

但是,使用HTML5文件API可能是一种选择,或者可以查看indexedDB。我没有尝试过它们,您可能会在使用它们时发现它们自己的局限性。

在这里找到两个类似的问题,大家可以看看

是否可以将文件

对象保存在本地存储中,然后在用户返回页面时通过文件读取器重新加载文件?

如何在本地存储中保存和还原 File 对象

很容易将

文件存储在索引数据库中。 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 的问题,告诉我它是否无法正常工作。