我有一个包含上传文件的列表:
let files = [File, File, File...];
和另一个要比较的上传文件:
let file = ...;
我想检查列表中是否存在file
(通过比较name/width/height/size/type
);
这是我的方式:
let f = files.find(function (x) {
return x.name === file.name && x.type === file.type &&
x.width === file.width && x.height === file.height &&
x.size === file.size;
});
if (f) {
// exist
}
但x.width
,x.height
,file.width
和file.height
始终返回undefined
。
undefined
总是等于undefined
(当然=))),但这不是我的意思,我想要获得真正的价值。
感谢this answer,我已经编辑了一些但尚未完成的内容。
let f = files.find(function (x) {
let x_img = new Image();
x_img.onload = function () {
let file_img = new Image();
file_img.onload = function () {
// we can compare x_img width/height and file_img width/height here
// but these functions look like the callback function
// so we can't delay to get width and height
};
file_img.src = window.URL.createObjectURL(file);
};
x_img.src = window.URL.createObjectURL(x);
// the main predicate here
return x.name === file.name && x.size === file.size && x.type === file.size &&...
// and how to compare width and height?
});
你能帮我完成代码吗?谢谢!
答案 0 :(得分:1)
获取naturalHeight
和var x = {
name: "crayola-rango.jpg",
type: "image/jpeg",
width: 896,
height: 259,
size: 37596
}; //file to compare
function find(x, files, callback) {
var len = files.length,
i,
_find = false,
fun = function (file, callback) {
var img = new Image();
img.onload = function () {
// no longer need to read the blob so it's revoked
window.URL.revokeObjectURL(file);
var width = img.naturalWidth,
height = img.naturalHeight;
if (x.name === file.name && x.type === file.type && x.width === width && x.height === height && x.size == file.size) {
callback(file);
_find = true;
}
}
img.src = window.URL.createObjectURL(file);
};
for (var i = 0; i < len; i += 1) {
if (_find) {
break;
}
fun(files[i], callback);
}
}
//only test
var file = document.getElementById("files");
file.addEventListener("change", function () {
//call this
find(x, file.files, function (file) {
console.log(file);
});
});
,如下所示
<input id="files" type="file" multiple>
data