将文件列表保存到 $.cookie

Saving FileList to $.cookies

本文关键字:cookie 保存 文件 列表      更新时间:2023-09-26

我有一个这样的文件列表:

FileList {0: File, 1: File, 2: File, File…}

刷新页面后,我需要记住这些文件。如何将它们保存到饼干中?(或者有没有更好的方法?现在我这样做$.cookie("result", files); files = $.cookie("result");但这得到了我无法解析的 [对象文件列表]。将files转换为JSON也不起作用。

任何想法如何保存文件列表,以便在页面刷新后可以循环它?

编辑:也许我应该注意,我从用户输入中获取文件列表,例如"选择文件"。

分配文件:

网页部分:

<input type="file" id="files" name="file" multiple />

JS部分:

$('#files').on('change', readFiles);
function readFiles(event) {
     var files = event.target.files; //has FileList {0: File, 1: File, 2: File, File…}
     $.cookie.json = true; //converts FileList to json (is correct).
     $.cookie("result", files); //cookie registering also works (atleas with strings) 
     files = $.cookie("result"); //get undefined as a result
     for (var i = 0, f; f = files[i]; i++) {
       var reader = new FileReader();
       reader.readAsText(f, 'utf-8');
     }
}

在原始代码中,代替:

reader.readAsText(f, 'utf-8');

你想要:

reader.readAsText(f.name, 'utf-8');

如果尚未打开它,则可能需要 JSON 选项,该选项会自动将对象转换为存储上的 JSON 字符串,然后在检索时自动转换为对象。它看起来像:

$.cookie.json=true;

这是文档:https://github.com/carhartl/jquery-cookie/tree/v1.4.1#json

注意:虽然根据规范,每个 cookie 的最大大小是无限的,但实际上它因浏览器而异。如果列表中有 150 个文件,则可能已达到限制,并且$.cookie对象拒绝该值。有关最大大小的更多信息,请参阅此处:网络浏览器 cookie 密钥的最大大小是多少?

要避免此限制,请划分列表或使用网络存储。

更好的解决方案是通过GET或POST将文件列表存储在服务器上,并让服务器提供允许检索的会话cookie。如果使用 PHP,请参阅 PHP 会话。