如何在node.js中处理multipart / form-data

时间:2012-11-01 09:32:30

标签: forms node.js multipartform-data

我使用多部分表单数据从客户端上传图像文件。我想接收并使用node.js将其作为服务器端的文件写入。

<html>
    <body>
        <form action="url" method="post" enctype="multipart/form-data">
            <input type="text" name="imageName">
            <input type="file" name="sam">
        </form>
    </body>
</html>

这是我的客户端代码。如何在服务器端处理此文件。

2 个答案:

答案 0 :(得分:2)

以下链接重复提问。

Uploading images using Node.js, Express, and Mongoose

以下是示例:

// Expose modules in ./support for demo purposes
require.paths.unshift(__dirname + '/../../support');

/**
 * Module dependencies.
 */

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

var app = express.createServer(
  // connect-form (http://github.com/visionmedia/connect-form)
  // middleware uses the formidable middleware to parse urlencoded
  // and multipart form data
  form({ keepExtensions: true })
);

app.get('/', function(req, res){
  res.send('<form method="post" enctype="multipart/form-data">'
    + '<p>Image: <input type="file" name="image" /></p>'
    + '<p><input type="submit" value="Upload" /></p>'
    + '</form>');
});

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

  // connect-form adds the req.form object
  // we can (optionally) define onComplete, passing
  // the exception (if any) fields parsed, and files parsed
  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');
    }
  });

  // We can add listeners for several form
  // events such as "progress"
  req.form.on('progress', function(bytesReceived, bytesExpected){
    var percent = (bytesReceived / bytesExpected * 100) | 0;
    process.stdout.write('Uploading: %' + percent + '\r');
  });
});

app.listen(3000);
console.log('Express app started on port 3000');

如果您的问题未得到解决,请访问 this link 。这是一篇关于文件上传的好文章。

答案 1 :(得分:-3)

您可以使用请求模块发送多部分请求。以下是示例代码:

var jsonUpload = {  };
var formData = {
    'file': fs.createReadStream(fileName),
    'jsonUpload': JSON.stringify(jsonUpload)
};
var uploadOptions = {
    "url": "https://upload/url",
    "method": "POST",
    "headers": {
        "Authorization": "Bearer " + accessToken
    },
    "formData": formData
}
var req = request(uploadOptions, function(err, resp, body) {
    if (err) {
        console.log('Error ', err);
    } else {
        console.log('upload successful', body)
    }
});