表单 – 如何处理node.js中的multipart / form-data

前端之家收集整理的这篇文章主要介绍了表单 – 如何处理node.js中的multipart / form-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>

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

解决方法

以下链接重复提问.

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('/',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 .这是一篇关于文件上传的好文章.

原文链接:https://www.f2er.com/html/227067.html

猜你在找的HTML相关文章