Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 246
Jan Petzold Avatar asked Nov 09 '22 22:11

Jan Petzold


1 Answers

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;
}
like image 70
Vitor Mori Avatar answered Nov 14 '22 21:11

Vitor Mori