0

My node.js server receives data from a form with an ajax post request. Form enctype is "multipart/form-data". I send three strings and one image and the best way I've found to access these data is by using the "multiparty" module. This is the situation

dispatcher.addListener("post", "/admin/req", function(req, res) {
  // parse a file upload
var form = new multiparty.Form({uploadDir: __dirname + "/tmp"});

form.parse(req, function(err, fields, files) {

  console.log(util.inspect({fields: fields, files: files}));
  console.log(files['img_event']);
  });
 });

and this is the outpout

//first log
     { fields: 
       { name_event: [ 'blablabla' ],
         data_event: [ 'blabla' ],
        },
      files: { img_event: [ [Object] ] } }

//second log
    [ { fieldName: 'img_event',
        originalFilename: 'screenshot 2014-10-11 16:57:54.png',
        path: '/home/myusername/Desktop/nodeapp/tmp/15620-v12gsy.png',
        headers: 
         { 'content-disposition': 'form-data; name="img_evento"; filename="Schermata del 2014-10-11 16:57:54.png"',
           'content-type': 'image/png' },
        ws: 
         { _writableState: [Object],
           writable: true,
           domain: null,
           _events: [Object],
           _maxListeners: 10,
           path:  '/home/myusername/Desktop/nodeapp/tmp/15620-v12gsy.png',
           fd: null,
           flags: 'w',
           mode: 438,
           start: undefined,
           pos: undefined,
           bytesWritten: 149910,
           closed: true },
        size: 149910 } 

now, if i try to access the property "path" or any other by:

  console.log(files['img_event'].path);
  or
  console.log(files['img_event']['path'];

it always returns "undefined".

What is wrong ?

1 Answer 1

3

Because, files['img_event'] is an Array, not an Object. You can confirm that like this

console.log(Object.prototype.toString.call(files['img_event']));
// [object Array]

So, you need to access the first element in the array, like this

files['img_event'][0].path
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.