node+express4+multiparty实现简单文件上传

文件上传

var fs = require('fs');
var express = require('express');                                                                                                                      
var multiparty = require('multiparty');

var app = express();


 /*文件上传*/
app.post('/uploadimg', function(req, res, next){
    //生成multiparty对象,并配置上传目标路径
    var form = new multiparty.Form({uploadDir: './uploads'});
    //上传完成后处理
    form.parse(req, function(err, fields, files){
        var inputFile = files.file[0];
        var uploadedPath = inputFile.path;
        var dstPath = './uploads/' + inputFile.originalFilename;
        fs.rename(uploadedPath, dstPath, function(err) {
            if(err){
                console.log('rename error: ' + err);
            } else {
                console.log('rename ok');
            }
        });
        files.file.path = dstPath;
        var data = files;
        
        res.send(data);
    });
});

app.listen(3000,function(){
    console.log("start:http://localhost:3000/uploadimg")
})

 

posted @ 2017-04-10 14:02  _zhiqiu  阅读(1669)  评论(0编辑  收藏  举报