我一直在寻找解决方案,尽管同一主题有很多答案,但我无法找出代码中的问题。
问题是,我只能使用此 API 读取第一个文件输入。
如果我 console.log(e.target.files[1]);
我正在使用 vue 2。这是我的代码。
对于我的三个输入
<input type="file" name="file[]" @change="img1">
<input type="file" name="file[]" @change="img2">
<input type="file" name="file[]" @change="img3">
img1(e){
console.log(e.target.files[0]);
this.readFile(e,'img1',0);
},
img2(e){
console.log(e.target.files[1]);
this.readFile(e,'img2',1);
},
img3(e){
console.log(e.target.files[2]);
this.readFile(e,'img3',2);
},
这是我的 readFile 方法
readFile(e,img,i) {
let self=this;
if(window.FileReader) {
var file = e.target.files[i];
var reader = new FileReader();
if (file) {
let type=e.target.files[i].type;
console.log(type);
if(!this.cheackType(type)){
this.showTypeWarn('Invalid Image Formate', 'Please Upload jpg or a png file only');
return
}
reader.readAsDataURL(file);
} else {
// img.css('display', 'none');
// img.attr('src', '');
}
reader.onloadend = function (e) {
self.data.img=reader.result;
}
}
}
谢谢。
最佳答案
当您执行 console.log(e.target.files[i]);
时,您正在访问触发事件的元素的第 i 个文件。您应该尝试使用 console.log(e.target.files[0]);
访问每个输入的第一个文件。
关于javascript - 如何在js中使用FileReader API读取多个文件输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45314410/