尝试使用ng-file-upload和multiparty上传文件来上传文件

时间:2016-04-07 05:10:32

标签: javascript angularjs node.js file-upload mean-stack

我正在尝试使用ng-file-upload和multiparty上传文件,但我不断得到 files.file undefined 错误,我不确定这个问题是否由ng-引起文件上传或多方,我花了差不多20个小时......

这是我的代码 users.client.view.html

<div class="modal-footer">
   <div class="btn-group">
       <label title="Upload" for="fileInput" class="btn btn-primary">
       <input type="file" accept="image/*" id="fileInput" class="hide">
       Upload new image
       </label>
   </div>
   <button  ng-click="uploadAvatar(croppedAvatarImage)" type="button" class="btn btn-primary">Save changes</button>
</div>

users.client.controller.js

$scope.uploadAvatar = function(image) {
    $scope.uploadInProgress = true;

    $scope.uploadProgress = 0;
        if (angular.isArray(image)) {
            image = image[0];
        }
        Upload.upload({
            url: '/api/v1/user/me/avatar',
            headers: {
                'Content-Type': 'multipart/form-data'
            },
            method: 'POST',
            data: {
                file: image
            }
        }).success(function(data, status, headers, config) {
            console.log("upload success!");
            $scope.$apply();
        }).error(function(err) {
            $scope.uploadInProgress = false;
            console.log("upload failed!");
    });
};

users.profile.server.controller.js

exports.uploadAvatar = function(req, res) {
    var form = new multiparty.Form();
    form.parse(req, function(err, fields, files) {

        Object.keys(files).forEach(function(name) {
            console.log('got file named ' + name);
        });

        console.log(files, files.file);

        var file = files.file[0]; // HERE THE PROGRAM CRASHED BY THE ERROR "Cannot read property '0' of undefined"
        var contentType = file.headers['content-type'];
        var extension = file.path.substring(file.path.lastIndexOf('.'));
        var destPath = '/' + user.id + '/profile' + '/' + uuid.v4() + extension;

        var headers = {
            'x-amz-acl': 'public-read',
            'Content-Length': file.size,
            'Content-Type': contentType
        };
        var uploader = s3Client.upload(file.path, destPath, headers);

        uploader.on('error', function(err) {
            res.status(500).send(err);
            //TODO handle this
        });

        uploader.on('end', function(url) {
            //TODO do something with the url
            console.log('file opened:', url);
        });
    });
};

2 个答案:

答案 0 :(得分:1)

文件是一个对象,其中属性名称是字段名称,值是文件对象的数组。因此,您尝试将名称添加到字段并使用它来获取文件数组。

在users.client.view.html中,添加名称属性:

<input type="file" accept="image/*" id="fileInput" name="fileInput" class="hide">

在users.profile.server.controller.js中:

更改以下代码

var file = files.file[0];

var file = files.fileInput[0];

答案 1 :(得分:0)

好的我终于想通了,我实际上是在尝试将Base64作为文件上传,因为我得到的img来自ngCrop,这是一个Base64字符串,所以它肯定无法在中找到档案字段。