随着多年来的情况发生变化,请考虑具有更多最新信息的更新答案!
由于许多新的 Node.js 库很快就会过时,而且示例相对较少,因此我想询问有关使用以下方法上传图像的问题:
Since many new Node.js libraries are quickly being rendered obsolete and there are relatively few examples anyways I want to ask about uploading images using:
- Node.js (v0.4.1)
- Express (1.0.7)
- 猫鼬 (1.1.0).
其他人是如何做到的?
我发现:node-formidable,但我一般不熟悉上传图片所以我想学习使用 Node.js 和 Express 的一般知识和方法.
I've found: node-formidable, but I am new to uploading images in general so I want to learn general stuff and ways of doing so using Node.js and Express.
推荐答案我将第一次回答我自己的问题.我直接从源代码中找到了一个示例.请原谅可怜的缩进.我不确定在复制和粘贴时如何正确缩进.代码直接来自 Express multipart/form-data 示例.
I'll answer my own question for the first time. I found an example straight from the source. Please forgive the poor indentation. I wasn't sure how to indent properly when copying and pasting. The code comes straight from Express multipart/form-data example on GitHub.
// 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 (github/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.formplete(function(err, fields, files){ if (err) { next(err); } else { console.log(' uploaded %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 + ''); }); }); app.listen(3000); console.log('Express app started on port 3000');更多推荐
使用 Node.js、Express 和 Mongoose 上传图片
发布评论