使用node.js读取对象属性

时间:2022-12-20 16:58:53

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

我的node.js服务器从带有ajax post请求的表单接收数据。表格enctype是“multipart / form-data”。我发送三个字符串和一个图像,我发现访问这些数据的最佳方法是使用“multiparty”模块。情况就是这样

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:

现在,如果我尝试通过以下方式访问属性“path”或任何其他属性:

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

it always returns "undefined".

它总是返回“未定义”。

What is wrong ?

哪里不对 ?

1 个解决方案

#1


3  

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

因为,files ['img_event']是一个数组,而不是一个Object。你可以这样确认一下

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

#1


3  

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

因为,files ['img_event']是一个数组,而不是一个Object。你可以这样确认一下

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