Jan Petzold
Jan Petzold

Reputation: 1571

Get file property via hasOwnProperty

I have an HTML5 file upload dialogue/dropzone which will give me something like this:

event.dataTransfer.files

Now I see that there are some (mandatory?) properties set for each File object:

https://developer.mozilla.org/en-US/docs/Web/API/File

like file.name, file.lastModifiedDate and so on. I can get the values this way

event.dataTransfer.files.item(0).name

but NOT check whether the property actually exists this way:

event.dataTransfer.files.item(0).hasOwnProperty('name')

I learned that it is a good practice to check properties for existence with hasOwnProperty() but that does not fit here. Why is that so? Is it because file.name is somehow "mandatory"? But why is the value just stored somewhere up in the prototype chain?

Upvotes: 5

Views: 415

Answers (1)

Vitor Mori
Vitor Mori

Reputation: 83

I don't have the explanation why hasOwnProperty does not work, but I created the following function that may receive event.dataTransfer.files.item(0) as input and return an object with all available properties:

function extractFileMetadada(file) {
    var r = {};
    var a = ['lastModified','lastModifiedDate','name','size','type','fileName','fileSize','webkitRelativePath'];

    for (var i=0; i<a.length; i++) {
        if (typeof file[a[i]] !== 'undefined')
            r[a[i]] = file[a[i]];
    }

    return r;
}

Upvotes: 1

Related Questions