javascript - 无法预览表单中的多个上传文件
问题描述
在多部分表单中,我可以使用以下方法预览单个上传图像:
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
let image = new Image();
image.src = `${e.target.result}`;
image.className = "img-thumbnail"
let closeBtn = `<button type="button" class="close"></button>`;
let wrapper = $('<div class="image-wrapper" />');
$('#images-to-upload').append(wrapper);
$(wrapper).append(image);
$(wrapper).append(closeBtn);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#imgInput").change(function () {
readURL(this);
});
但我想预览所有上传的图片,所以我通过添加一个 for 循环对上面的代码进行了调整:
function readURL(input) {
if (input.files && input.files[0]) {
let files = input.files;
for (var i = 0; i < input.files.length; i++) {
var reader = new FileReader();
reader.onload = function (e) {
let image = new Image();
image.src = `${e.target.result[i]}`;
image.className = "img-thumbnail"
let closeBtn = `<button type="button" class="close"></button>`;
let wrapper = $('<div class="image-wrapper" />');
$('#images-to-upload').append(wrapper);
$(wrapper).append(image);
$(wrapper).append(closeBtn);
}
};
reader.readAsDataURL(input.files[i]); // error here
}
}
但现在我得到这个错误:
143 Uncaught TypeError: Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'
我怎样才能解决这个问题?
解决方案
这是因为reader.readAsDataURL(input.files[i]);
在循环之外。但这不是你这样做的方式。FileReader
一次只能处理一个文件。这意味着您必须为FileReader
输入中的每个图像创建一个实例。
为了便于阅读,我建议将其拆分为 2 个函数。
function previewImage(file) {
const reader = new FileReader();
reader.onload = function (e) {
let image = new Image();
image.src = e.target.result;
image.className = "img-thumbnail";
let closeBtn = `<button type="button" class="close"></button>`;
let wrapper = $('<div class="image-wrapper" />');
$("#images-to-upload").append(wrapper);
$(wrapper).append(image);
$(wrapper).append(closeBtn);
};
reader.readAsDataURL(file);
}
function readURL(input) {
if (input.files.length) {
Array.from(input.files).forEach((file) => previewImage(file));
}
}
我做了一些改变:
if (input.files.length) {
- 文件输入总是有文件FileList
对象,所以不需要检查它是否存在,你只需检查它是否有长度,这意味着至少存在一个文件Array.from(input.files)
- 转换FileList
为常规数组,您可以使用数组函数,例如forEach
其余的几乎相同。在image.src = e.target.result;
中,无需将其设为字符串,因为它已经是字符串。类上的结果集FileReader
也不能是数组。
推荐阅读
- json - 从 url 调用 json 文件
- angular - 使用 FormArrayControl Angular 从动态表访问数据
- amazon-web-services - 从事件规则中捕获数组键的特定值及其在 Input Transformer 中的值
- r - 保存用户定义的变量并在 Shiny 中运行 R scipt
- json - 如何将来自 API 的 JSON 转换为 DATAFRAME pyspark?
- python - 使用 SQLAlchemy 和 SQL Server 返回插入行的主键
- sqlite - Golang:即使在 db.Close() 上,集成测试也会命中同一个数据库实例
- electron - 电子钥匙释放
- android - 任务 ':shared:podInstall' 执行失败
- python - Opencv findContours() 返回顺序