2

I'm trying to post a file from a mobile triggerio app to a nodejs service. The request hits the post method, but the fails because the form object is null in the request obj. (TypeError: Cannot call method 'complete' of undefined)

I've adapted the code from the accepted answer in this post : Uploading images using Node.js, Express, and Mongoose

This is my current nodejs code:

var express = require('express')
  , form = require('connect-form');

var app = express.createServer(
  form({ keepExtensions: true })
);

app.post('/fileupload', function(req, res, next){

  //req. form is nulL
  req.form.complete(function(err, fields, files){
    if (err) {
      next(err);
    } else {
      console.log('\nuploaded %s to %s'
        ,  files.image.filename
        , files.image.path);
      res.redirect('back');
    }
  });

  req.form.on('progress', function(bytesReceived, bytesExpected){
    var percent = (bytesReceived / bytesExpected * 100) | 0;
    process.stdout.write('Uploading: %' + percent + '\r');
  });
});

app.listen(process.env.PORT);
console.log("express started");

And this is my upload method in triggerio:

function uploadFile (file){
    forge.request.ajax({
        url: 'http://resttrigger.aykarsi.c9.io/fileupload',
        type: 'POST',
        files: [file],
        fileUploadMethod: 'raw',
        dataType: 'json',
        success: function (data) {
            forge.logging.log("success " + data);
        },
        error: function (e) {
            forge.logging.log("error " + e);
        }
    });
}
Community
  • 1
  • 1
AyKarsi
  • 9,435
  • 10
  • 54
  • 92

1 Answers1

2

Using fileUploadMethod: 'raw' might be the problem here: it means that the request body is just a binary blob, rather than the multipart-encoded form which your node code expects.

For reference, here is a minimal handler that will save uploaded files into /tmp:

exports.upload = function(req, res){
    var filename = '/tmp/' + new Date().getTime();

    console.log(JSON.stringify(req.files));

    // replace "test" with your actual form field name
    fs.readFile(req.files["test"].path, function (err, data) {
        fs.writeFile(filename, data, function (err) {
            res.send({filename: filename});
        });
    });
};
James Brady
  • 27,032
  • 8
  • 51
  • 59