我正在使用多部分表单数据从客户端上传图像文件.我想接收并使用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');