在express项目中使用formidable & multiparty实现文件上传

安装 formidable,multiparty 模块

npm install formidable,multiparty –save -d

表单上传

<form id="addForm" enctype="multipart/form-data">
    <fieldset>
        <h3>创建用户</h3>
        姓名:<input type="text" name="name" placeholder="请输入姓名"/>
        <br> <br>
        头像:<input type="file" name="icon" multiple="multiple">
        <br> <br>
        <input type="button" onclick="submit1()" value="提交(formidable处理)"/>
        <input type="button" onclick="submit2()" value="提交(multiparty处理)"/>
        <br> <br>
    </fieldset>
</form>

 ajax将表单内容发送至后台接口:

<script src="/js/jquery-1.9.1.min.js"></script>
<script>
function submit1(){

var data = new FormData($('#addForm')[0]); //获取表单内容

ajaxFormPost("/api/user/addUser_with_formidable",data,function(data){ //ajax提交表单
console.log("formidable处理结果:",data);

alert(data.code+":"+data.msg);

});

}

function submit2(){
var data = new FormData($('#addForm')[0]); //获取表单内容

ajaxFormPost("/api/user/addUser_with_multiparty",data,function(data){ //ajax提交表单
console.log("multiparty处理结果:",data);

alert(data.code+":"+data.msg);

});
}


//ajax Post方法封装
function ajaxFormPost(url,formData,callBack){
$.ajax({
type:'POST',
dataType:'text',
processData: false, // 告诉JSLite不要去处理发送的数据
contentType: false, // 告诉JSLite不要去设置Content-Type请求头
data:formData,
url:url,
success:function(data){
data = JSON.parse(data);
callBack(data);
},
error:function(data){
console.log('error:',data)
callBack(data);
}
});
}

</script>

 

注意:express项目中app.js一定引入body-parser模块

var bodyParser = require('body-parser');

app.use(bodyParser.json());  // form表单解析必须
app.use(bodyParser.urlencoded({ extended: false }));

 

方式1:formidable解析表单关键代码


exports.formidableFormParse = function(req,callback){

var form = new formidable.IncomingForm({
encoding:"utf-8",
uploadDir:"public/upload", //文件上传地址
keepExtensions:true //保留后缀
});
form.parse(req, function(err, fields, files) {
var obj ={};
Object.keys(fields).forEach(function(name) { //文本
console.log('name:' + name+";filed:"+fields[name]);
obj[name] = fields[name];
});

Object.keys(files).forEach(function(name) { //文件
console.log('name:' + name+";file:"+files[name].path);
obj[name] = files[name];
});

callback(err,obj);
});
}
 
 
返回值obj内容:

{
“name”: “wuwanyu”,
“icon”: {
“size”: 8666,
“path”: “public\upload\upload_713dad980d7b7dce0847476820f8b1d4.jpg”,
“name”: “4eff22a5d3d8341d3bf472adbb151c18.jpg”,
“type”: “image/jpeg”,
“mtime”: “2016-04-06T13:18:15.508Z”
}
}

 

 

方式2:multiparty解析表单关键代码

exports.multipartyFormParse = function(req,callback){
    var form = new multiparty.Form({
        encoding:"utf-8",
        uploadDir:"public/upload",  //文件上传地址
        keepExtensions:true  //保留后缀
    })

    form.parse(req, function(err, fields, files) {
        var obj ={};
        Object.keys(fields).forEach(function(name) {  //文本
            console.log('name:' + name+";filed:"+fields[name]);
            obj[name] = fields[name];
        });

        Object.keys(files).forEach(function(name) {  //文件
            console.log('name:' + name+";file:"+files[name]);
            obj[name] = files[name];
        });

        callback(err,obj);
    });
}

 

返回值obj的内容(一个文件时):

{
“name”: [ “tom”],
“icon”: [
{
“fieldName”: “icon”,
“originalFilename”: “4eff22a5d3d8341d3bf472adbb151c18.jpg”,
“path”: “public\upload\SKt_XEwcxnBD_4qc6qI-PBw9.jpg”,
“headers”: {
“content-disposition”: “form-data; name=\”icon\”; filename=\”4eff22a5d3d8341d3bf472adbb151c18.jpg\”“,
“content-type”: “image/jpeg” },
“size”: 8666
}
]
}

 

返回值(多个文件时 ):

{
“name”: [ “tom” ],
“icon”: [
{
“fieldName”: “icon”,
“originalFilename”: “3bd870116ff9708f5141aa8a374aeabf.jpg”,
“path”: “public\upload-MVUwGgwT9DbGCZh50yBGLHy.jpg”,
“headers”: {
“content-disposition”: “form-data; name=\”icon\”; filename=\”3bd870116ff9708f5141aa8a374aeabf.jpg\”“,
“content-type”: “image/jpeg” },
“size”: 25754
},
{
“fieldName”: “icon”,
“originalFilename”: “4eff22a5d3d8341d3bf472adbb151c18.jpg”,
“path”: “public\upload\HJIOAYHXjluOTtWZ2M-qwHUq.jpg”,
“headers”: {
“content-disposition”: “form-data; name=\”icon\”; filename=\”4eff22a5d3d8341d3bf472adbb151c18.jpg\”“,
“content-type”: “image/jpeg” },
“size”: 8666
}
]
}

 

总结:

formidable和multiparty都能实现解析表单的功能,返回值的数据结构和字段名称稍有不同。

formidable解析结果是json数据格式的。multiparty 返回值是数组格式的,解析同一个字段多个值时,比如上传多张图片,使用multiparty更合适。

文件将被上传到public/upload目录下,如果要移动文件位置,可以使用fs模块的rename方法。

 
Github项目地址: https://github.com/wuwanyu/formidable_multiparty_demo

 

项目运行效果图

(1)formidable表单上传及处理结果:

image

(2)multipaty表单上传及处理结果:

image

 

posted @ 2016-04-06 23:12  蓝之矾  阅读(5243)  评论(4编辑  收藏  举报