2

我正在尝试将文件从移动 triggerio 应用程序发布到 nodejs 服务。请求命中 post 方法,但由于请求 obj 中的表单对象为空而失败。(TypeError:无法调用未定义的方法“完成”)

我已经从这篇文章中接受的答案中修改了代码:使用 Node.js、Express 和 Mongoose 上传图像

这是我当前的 nodejs 代码:

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");

这是我在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);
        }
    });
}
4

1 回答 1

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});
        });
    });
};
于 2012-05-25T16:18:23.383 回答