expressjs解析表格数据包括文件和Json

时间:2013-10-19 00:57:42

标签: parsing angularjs file-upload express http-post

我在Angularjs的一个请求中发布了许多文件+ Json数据到expressjs

Angularjs:

function myController($scope, $routeParams, $location, $http) {
    $scope.files = [];
    $scope.$on("fileSelected", function (event, args) {
           $scope.$apply(function () {            
            //add the file object to the scope's files collection
            $scope.files.push(args.file);
        });
        });

    $scope.submit = function() {
        $scope.json = {
            phone: this.phone,
            description: this.description,
        };


        $http({
            method: 'POST',
            url: '/phones/'+ $routeParams.phoneId,
            //IMPORTANT!!! You might think this should be set to 'multipart/form-data' 
            // but this is not true because when we are sending up files the request 
            // needs to include a 'boundary' parameter which identifies the boundary 
            // name between parts in this multi-part request and setting the Content-type 
            // manually will not set this boundary parameter. For whatever reason, 
            // setting the Content-type to 'false' will force the request to automatically
            // populate the headers properly including the boundary parameter.
            // headers: { 'Content-Type': false },
            //This method will allow us to change how the data is sent up to the server
            // for which we'll need to encapsulate the model data in 'FormData'
            transformRequest: function (data) {
                var formData = new FormData();
                //need to convert our json object to a string version of json otherwise
                // the browser will do a 'toString()' on the object which will result 
                // in the value '[Object object]' on the server.
                formData.append("model", angular.toJson(data.model));
                //now add all of the assigned files
                for (var i = 0; i < data.files; i++) {
                    //add each file to the form data and iteratively name them
                    formData.append("file" + i, data.files[i]);
                }
                return formData;
             },
            //Create an object that contains the model and files which will be transformed
            // in the above transformRequest method
            data: { model: $scope.seller_submit, files: $scope.files }

        }).
        success(function (data, status, headers, config) {
            alert("success!");
        }).
        error(function (data, status, headers, config) {
            alert("failed!");
        });

     };
};

Expressjs 3.x:

app.use(express.bodyParser({ keepExtensions: true, uploadDir: __dirname + '/public/uploads' }));

要处理请求我只使用:

console.log(req.body); //print Json is ok but can not print files info
console.log(req.files); // can not print files info
 //Both of above handlers generate the same error "Can not call method "replace" of undefined.

我认为express的问题无法解析多文件上传请求。请帮忙!

1 个答案:

答案 0 :(得分:0)

我使用带有角度的快速3.x.我刚刚在我的角度服务中创建了一个函数来上传带有JSON信息的照片。

_uploadPhotoWithInfo = function(files, info){
var fd = new FormData();
fd.append("photo", files[0]);
for (var i in info){
  fd.append(i,info[i]);
}
$http.post('/upload', fd, {
    withCredentials: true,
    headers: {'Content-Type': undefined },
    transformRequest: angular.identity
}).success(function(result){
  alert("success!");
});

}

在express中,信息对象显示在req.body中,文件显示在req.files中。