这篇文章node.js+Android(使用HttpURLConnection和HttpClient)实现文件上传(见 http://www.linuxidc.com/Linux/2012-02/53532.htm ),使用的是formidable,上篇文章介绍了node.js connect 安装、介绍与实例(见 http://www.linuxidc.com/Linux/2012-02/53528.htm ),那就用connect写一个上传的例子。
主程序代码如下,保存为bodyParser.js,放在敲安装命令的目录下:
[Javascript]
- var connect = require(‘connect’);
- var app = connect()
- .use(connect.static(__dirname + ‘/public’))
- .use(connect.bodyParser({uploadDir:__dirname +‘/file’,keepExtensions:true}))
- .use(connect.logger())
- .use(function(req, res, next){
- if (‘GET’ != req.method) return next();
- res.statusCode = 302;
- res.setHeader(‘Location’, ‘form.html’);
- res.end();
- })
- .use(function(req, res){
- res.setHeader(‘Content-Type’, ‘text/html’);
- res.write(‘<p>thanks ‘ + req.body.name + ‘</p>’);
- res.write(‘<ul>’);
- console.log(req.body);
- console.log(req.files);
- if (Array.isArray(req.files.images)) {
- req.files.images.forEach(function(image){
- var kb = image.size / 1024 | 0;
- res.write(‘<li>uploaded ‘ + image.name + ‘ ‘ + kb + ‘kb</li>’);
- });
- } else {
- var image = req.files.images;
- var kb = image.size / 1024 | 0;
- res.write(‘<li>uploaded ‘ + image.name + ‘ ‘ + kb + ‘kb</li>’);
- }
- res.end(‘</ul>’);
- });
- app.listen(8080);
- console.log(‘Server started on port 8080’);
[html]
- <html>
- <body>
- <form action=“/” method=“post” enctype=“multipart/form-data”>
- <input type=“text” name=“name” placeholder=“Name:” />
- <input type=“file” name=“images” multiple=“multiple” />
- <input type=“submit” value=“Upload” />
- </form>
- </body>
- </html>
效果同 node.js+android(使用HttpURLConnection和HttpClient)实现文件上传,需要的话查看这篇文章 见http://www.linuxidc.com/Linux/2012-02/53532.htm。