Reputation: 1604
I'm using angularJS for my frontend and sails.js/expressjs for my backend. I'm implementing a file upload function using ng-file-upload, and strangely the file never seem to upload to the server successfully... this is my angularJS code:
$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);
});
}
});
And this is my sails.js code:
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
});
});
},
And I always get the following response from server:
Object {message: "0 file(s) uploaded successfully!", files: Array[0]}
When I check the corresponding server upload destination folder, there's nothing.... anyone know why or could provide some help? Will really appreciate it!
Upvotes: 0
Views: 726
Reputation: 1604
Ok this question isn't a really smart one, I figured out where the problem is: the default fileFormDataName for ng-file-upload is "file", since I'm using req.file('avatar') on the server side, I should really add the following setting option in my angular code:
fileFormDataName: 'avatar',
which makes it look like so:
$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);
});
}
});
According to @Anupam Bhaskar's request, I've also added my HTML code for a file upload dropzone below:
<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>
Upvotes: 1