gpt4 book ai didi

javascript 文件读取器 : preview for images in multiple files batches

转载 作者:行者123 更新时间:2023-11-30 08:27:58 24 4
gpt4 key购买 nike

您好,我正在尝试使用 FileReader 实现创建多个文件上传预览的脚本。这是我的出发点

<input id="attachments" type="file" multiple="multiple" name="attachments">
<table id="file_info_attachments" class="table table-preview"></table>

我想做的是读取上传的文件列表,将它们的名称和大小放入 file_info_attachments 表(每个文件一行),棘手的部分是,如果它们是图像,请在同一行中添加预览。

我理想的预览应该是这样的

    <input id="attachments" type="file" multiple="multiple" name="attachments">
<table id="file_info_attachments" class="table table-preview">
<tr>
<td>No preview</td>
<td>file_1.txt</td>
<td>2000</td>
</tr>
<tr>
<td><img src="[IMAGE DATA]" /></td>
<td>file_2.png</td>
<td>2000</td>
</tr>
</table>

我的解析函数 scratch 是这样的:

function parseFiles(files, id) {
$("#file_info_" + id).html("");

if(files.length > 0) {
for (var i = 0; i < files.length; i++) {
$("#file_info_" + id).append("<tr><td class=\"preview preview_" + i + "\">No preview</td><td>" + files[i].name + "</td><td>Size: " + files[i].size + "</td></tr>");
if(/\.(jpe?g|png|gif)$/i.test(files[i].name) && typeof (FileReader) != "undefined") {
var reader = new FileReader();
reader.onload = function(e){
//obviously I cannot do that this way due to how reader.onload works
//$("#file_info_" + id + " .preview_" + i).html("<img src=\"" + e.target.result + "\" />");
};
reader.readAsDataURL(files[i]);
}
}
}
}

这就是我调用 parseFiles 函数的方式:

$(document).on("change", "#attachments", function(){
var files = $(this)[0].files;
parseFiles(files, "attachments");
});

我知道我可以通过将信息行附加到 reader.onload 函数而不是在 for 循环之后立即添加它来使其工作,但是,由于我正在处理不同类型的文件,我只想让它们保持有序并且如果它们是图像,只需更新预览字段。我怎样才能让 reader.onload 通过添加更新预览的内部 HTML

提前致谢。

最佳答案

不确定浏览器是否会保留用户选择多个文件的顺序实际上我非常有信心它在我的 FF 上按字母顺序排序,但要以与您相同的顺序显示图像进入 input.files 属性,只是不要使用 FileReader 来读取用户选择的文件

相反,您应该更喜欢 URL.createObjectURL()方法。

此方法是同步的,因此您不必处理不同的范围,而且,对于用户选择的文件,这只是指向存储在用户系统中的文件的直接指针,即,内存影响几乎为 0。

file.onchange = function(e) {
for (let i = 0; i < this.files.length; i++) {
let url = URL.createObjectURL(this.files[i]);
let img = new Image();
img.src = url;
document.body.appendChild(img);
// you can even free these 10bits you occupy in memory if you don't need the url anymore
img.onload = function() {
URL.revokeObjectURL(this.src);
}
console.log(this.files[i].name);
}
}
<input type="file" accept="image/*" multiple id="file">

关于javascript 文件读取器 : preview for images in multiple files batches,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42193452/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com