简体   繁体   中英

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". 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.

You can check it using instanceof keyword.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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