Sha*_*ins 8 javascript jquery fileapi dropzone.js
我似乎无法访问我的对象的宽度或高度键.
我正在使用dropzone.js,它有一个addFile事件,它返回文件和第一个参数.
所以:
var myDropzone = new Dropzone('#dropzone', {url: '/'});
myDropzone.on('addedFile', function(file) {
console.log(file);
});
Run Code Online (Sandbox Code Playgroud)
回调工作得很好,在我的控制台中我看到:

如您所见,显然有高度和宽度键可用.
myDropzone.on('addedFile', function(file) {
console.log(file.name); // returns the whole strong
console.log(file.width); // returns undefined
console.log(file['width']); // returns undefined
});
Run Code Online (Sandbox Code Playgroud)
继承人截图:

我的问题是,为什么名称可用,但不是宽度或高度?是因为他们是只读还是什么?如果是这样的话,甚至可以访问它吗?
该File.width属性是DropzoneJS扩展,不是核心File API的一部分; 它会在以后添加.
Dropzone将数据添加到事件触发时可以使用的文件对象.你可以访问
file.width,file.height如果它是一个图像..
如果适用的图像尺寸信息可通过时间的"thumbnail"事件发生.它不保证此事件之前进行设置.
文档不是很明确,只是暗示"生成缩略图时",但这是源的行为(请参阅createThumbnail/resize函数) - 生成缩略图时会收集图像大小.
可以看到初始行为,因为console.log(在浏览器中,例如Chrome,它将其视为类似console.dir)显示"实时"对象.这反过来又为浏览器在控制台中显示对象的现在分配属性之前完成异步缩略图生成和相关图像维度收集提供了足够的时间.(这也解释了为什么使用超时读取属性值有效 - 即使这不是一种可靠的方法.)
在另一方面,直接访问file.width部队仍然未设置属性,这会导致您立即评估undefined的"addedFile"回调.
所以只是为了清楚.正如user2864740所说,你需要等待"缩略图"事件.这将产生以下代码:
myDropzone.on('addedFile', function(file) {
myDropzone.on("thumbnail", function(file){
console.log(file);
console.log(file.width); // returns width
console.log(file['width']); // returns width
});
});
Run Code Online (Sandbox Code Playgroud)
您甚至可以在接受方法中使用它,如下所示:
myDropzone.on('accept', function(file, done){
myDropzone.on("thumbnail", function(file){
if(file.width != 728 && file.height != 90){
done("Resolution is not correct (Super Banner (728x90))");
} else {
done();
}
});
}
Run Code Online (Sandbox Code Playgroud)