简体   繁体   English

如何判断Javascript对象是否为文件?

[英]How can I tell if a Javascript object is a File?

I have a function that manipulates an object that contains an "upload" member that is of type File. 我有一个函数来处理一个对象,该对象包含文件类型为“上载”的成员。 I would like to detect that fact so that I can ignore it and skip over all objects of this type. 我想检测到这一事实,以便可以忽略它并跳过所有此类对象。

I tried a bunch of things in the console, but nothing seems to return "true". 我在控制台中尝试了一堆东西,但是似乎什么都没有返回“ true”。 Here's a transcript of my futile attempts from inside a console breakpoint: 这是我从控制台断点内部徒劳尝试的成绩单:

> values.avatar
{upload: File}
> values.avatar.upload
File {name: "29_Drawing Hands by Escher.jpg", lastModified: 1446580115000, lastModifiedDate: Tue Nov 03 2015 14:48:35 GMT-0500 (Eastern Standard Time), webkitRelativePath: "", size: 1314300, …}
> values.avatar.upload.isPrototypeOf(File)
false
> File
ƒ File() { [native code] }
> File.prototype
File {constructor: ƒ, …}
values.avatar.upload.isPrototypeOf(File.prototype)
false
> values.avatar.upload.prototype 
undefined
> File.isPrototypeOf
ƒ isPrototypeOf() { [native code] }
> File
ƒ File() { [native code] }
> values.avatar
{upload: File}
> File
ƒ File() { [native code] }
> File.__proto__
ƒ Blob() { [native code] }
> values.avatar.upload.__proto__
File {constructor: ƒ, …}
values.avatar.upload.isPrototypeOf(File.__proto__)
false
> values.avatar.upload.isPrototypeOf(Blob.__proto__)
false

Clearly I lack a fundamental understanding of how native types and prototypes work in Javascript. 显然,我对本机类型和原型如何在Javascript中工作缺乏基本的了解。

You can check it using instanceof keyword. 您可以使用instanceof关键字进行检查。

if (values.avatar.upload instanceof File)
  // yes, it's a File type.
else
  // no, it's not.

校验

values.avatar.upload instanceof File 

You can also test by it's prototype: 您还可以通过其原型进行测试:

if(values.avatar.upload.prototype === File.prototype) {
  // true
} else {
 // false
}

For instance, you may use: 例如,您可以使用:

File.prototype.isPrototypeOf(values.avatar.upload)

For eg. 例如。 the following will return true: 以下将返回true:

 var file = new File([""], 'text.txt'); console.log(File.prototype.isPrototypeOf(file)); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM