Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs: iterate over req.files properties

Tags:

node.js

I'm quite new to nodejs and sometimes I come across difficulties :) So for example. I'm sending an image file via AJAX and recieve it successfully in my app.

console.log(req.files) prints:

{
    img_1351078491675: {
        size: 354683,
        path: '/tmp/f29009b6dc914c2ab27e2c5fde13e7d8.jpg',
        name: 'nov10wallpaper-1_1600.jpg',
        type: 'image/jpeg',
        hash: false,
        lastModifiedDate: Wed Oct 24 2012 13: 36: 55 GMT + 0200(CEST),
        _writeStream: {
            path: '/tmp/f29009b6dc914c2ab27e2c5fde13e7d8.jpg',
            fd: 14,
            writable: false,
            flags: 'w',
            encoding: 'binary',
            mode: 438,
            bytesWritten: 354683,
            busy: false,
            _queue: [],
            _open: [Function],
            drainable: true
        },
        length: [Getter],
        filename: [Getter],
        mime: [Getter]
    }
}

Because the image has a timestamp I cannot access with req.files.img_. So I was using for(file in reg.files) to get it (forEach didn't work - no idea why. seems to be a normal hash/object). But now my problems actually start. How can I read out the attributes of that file? E.g. file.path doesn't work. It returns "undefined" but why?

Could someone please give me a hint to understand such basics?

like image 567
JimBob Avatar asked Dec 16 '22 18:12

JimBob


1 Answers

I believe forEach() is meant for arrays rather than objects, so that's probably why that didn't work.

If there is only (ever) one file, then:

var fileKey = Object.keys(req.files)[0];
var file = req.files[fileKey];

...or just:

var file = req.files[Object.keys(req.files)[0]];`

...will 'dig down one level' so you can do file.path or file.type. If there are (or might be) more than one:

var files = [];
var fileKeys = Object.keys(req.files);

fileKeys.forEach(function(key) {
    files.push(req.files[key]);
});

This will give you a list of files 'dug down one level', on which you can forEach().

Hope that helps!

like image 90
floatingLomas Avatar answered Jan 11 '23 14:01

floatingLomas