2016-04-07 63 views
0

我想使用ng文件上傳和多方上傳文件,但我不斷有一個files.file undefined錯誤,我也不太清楚這個問題是由NG-文件上傳或多方,我花了差不多20個小時這引起了.....試圖通過使用ng文件上傳和多方上傳文件上傳文件

這裏是我的代碼 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); 
     }); 
    }); 
}; 

回答

0

Ok I fina lly想通了這一點,我其實是試圖上傳一個Base64作爲一個文件,因爲我得到的img是從ngCrop,這是一個Base64字符串,所以它絕對不能在文件字段找到。

1

文件是一個對象其屬性名是字段名稱和值是文件對象的陣列。所以你可以嘗試向字段添加名稱並使用它來獲取文件數組。

在users.client.view.html,添加name屬性:

<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]; 
+0

感謝您的諮詢!但問題是,我嘗試** console.log(文件)**和輸出是{},這意味着什麼都沒有上傳到後端,但我真的無法找出哪個部分是點 – C0deZ

+0

我只能得到字段定義,但req.files總是空的 – C0deZ