【问题标题】:angular file upload+sails skipper upload no file角度文件上传+帆船长上传无文件
【发布时间】:2015-03-24 21:23:07
【问题描述】:

我的前端使用 angularJS,后端使用sails.js/expressjs。我正在使用 ng-file-upload 实现文件上传功能,奇怪的是文件似乎从未成功上传到服务器......这是我的 angularJS 代码:

$scope.$watch('data.chosenImageFile', function() {
    if ($scope.data.chosenImageFile) {
        console.log($scope.data.chosenImageFile);
        $scope.upload = $upload.upload({
            url: '/upload_user_avatar',
            method: 'POST',
            file: $scope.data.chosenImageFile
        }).progress(function(evt) {
            console.log('progress: ' + parseInt(100.0 * evt.loaded / evt.total));
        }).success(function(data, status, headers, config) {
            console.log(data);
        });
    }
});

这是我的sails.js 代码:

uploadUserAvatar: function(req, res) {
    req.file('avatar').upload(function(err, files) {
        if (err) return res.send(500, err);
        return res.json({
            message: files.length + ' file(s) uploaded successfully!',
            files: files
        });
    });
},

而且我总是从服务器收到以下响应:

Object {message: "0 file(s) uploaded successfully!", files: Array[0]}

当我检查相应的服务器上传目标文件夹时,什么都没有......有人知道为什么或可以提供一些帮助吗?真的很感激!

【问题讨论】:

    标签: angularjs upload sails.js


    【解决方案1】:

    好吧,这个问题不是很聪明,我发现问题出在哪里:ng-file-upload 的默认 fileFormDataName 是“file”,因为我使用的是 req.file('avatar')在服务器端,我真的应该在我的角度代码中添加以下设置选项:

            fileFormDataName: 'avatar', 
    

    这使它看起来像这样:

    $scope.$watch('data.chosenImageFile', function() {
        if ($scope.data.chosenImageFile) {
            console.log($scope.data.chosenImageFile);
            $scope.upload = $upload.upload({
                url: '/upload_user_avatar',
                method: 'POST',
                fileFormDataName: 'avatar',
                file: $scope.data.chosenImageFile
            }).progress(function(evt) {
                console.log('progress: ' + parseInt(100.0 * evt.loaded / evt.total));
            }).success(function(data, status, headers, config) {
                console.log(data);
            });
        }
    });
    

    更新

    根据@Anupam Bhaskar 的要求,我还在下面添加了用于文件上传放置区的 HTML 代码:

    <div ng-file-drop ng-if="!data.isUploading" ng-model="data.chosenImageFile" class="avatar-dropzone pull-left" drag-over-class="upload-dropzone" ng-file-change="avatarUpload.fileSelected('/upload_user_avatar', data.user, data)" multiple="false" allow-dir="true" accept="*">
       <div class="text-center upload-sign">+</div>
    </div>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-04
      • 1970-01-01
      • 2021-08-21
      • 2017-12-30
      • 2015-11-20
      • 2020-12-02
      • 1970-01-01
      • 2014-11-16
      相关资源
      最近更新 更多