这是我的代码:
var fr = new FileReader();
var readFiles;
var fileI;
var files;
fr.onload = () => {
readFiles.push(fr.result);
fileI ++;
if (fileI < files.length) {
fr.readAsDataURL(files[fileI]);
}
};
function getVideoImage(path, secs, callback) {
var me = this, video = document.createElement('video');
video.onloadedmetadata = function() {
if ('function' === typeof secs) {
secs = secs(this.duration);
}
this.currentTime = Math.min(Math.max(0, (secs < 0 ? this.duration : 0) + secs), this.duration);
};
video.onseeked = function(e) {
var canvas = document.createElement('canvas');
canvas.height = video.videoHeight;
canvas.width = video.videoWidth;
var ctx = canvas.getContext('2d');
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
var img = new Image();
img.src = canvas.toDataURL();
callback.call(me, img, this.currentTime, e);
};
video.onerror = function(e) {
callback.call(me, undefined, undefined, e);
};
video.src = path;
}
$uploadFiles.on("input", () => {
files = $uploadFiles[0].files;
var value = $uploadFiles[0].value;
fileI = 0;
readFiles = [];
fr.readAsDataURL(files[0]);
for (var i = 0; i < files.length; i++) {
var format = files[i].name.split(".").pop().toUpperCase();
var thumbnail;
getVideoImage(readFiles[i], 0, (img) => {
thumbnail = img;
});
if (fileFormat.video.includes(format)) {
propertiesData.FILES.contents[0].push({
thumbnail: thumbnail,
title: files[i].name,
file: readFiles[i]
});
} else if (fileFormat.image.includes(format)) {
console.log(readFiles);
console.log(i);
console.log(readFiles[i])
propertiesData.FILES.contents[1].push({
thumbnail: readFiles[i],
title: files[i].name,
file: readFiles[i]
});
} else if (fileFormat.audio.includes(format)) {
propertiesData.FILES.contents[2].push({
thumbnail: "Assets/Logo.PNG",
title: files[i].name,
file: readFiles[i]
});
} else {
alert("File Format Not Supported");
}
$("#properties-left-menu li[style='color: ${color[1]}']")
}
});
它将读取上载的文件,并将原始文件保存在数据对象(propertiesData)中。 问题是这部分:
console.log(readFiles);
console.log(i);
console.log(readFiles[i])
propertiesData.FILES.contents[1].push({
thumbnail: readFiles[i],
title: files[i].name,
file: readFiles[i]
});
console.log(readFiles);显示原始文件数组,例如this和 console.log(i);显示正确的索引 所以 console.log(readFiles [i]);应该显示原始文件字符串之一,但是只显示未定义的字符串。为什么?
答案 0 :(得分:1)
出于性能原因,浏览器控制台仅在以后评估引用(例如对象引用或数组)。因此,它并没有向您显示该日志语句在执行时的实际内容。
来自MDN:
请注意,如果您在最新版本的Chrome和Firefox中记录对象,则在控制台上登录的内容是对该对象的引用,不一定是您当时的对象的“值”调用console.log(),但这是单击对象时打开该对象时的值。
要获取当时的实际内容,请使用
console.log(readFiles.toString());
然后您将看到,由于FileReader.readAsDataURL()是异步执行的,因此此时数组仍为空。
进一步阅读: