Reputation: 1758
I'm attempting to upload a file to a sails.js application server using this directive: ng-file-upload
My client side to upload an already selected image is this:
$upload.upload({
url:'upload/item-image',
headers:{
'Content-Type': 'multipart/form-data'
},
data:{blah:'blah'},
file: $scope.uploadFile,
fileName:$scope.uploadFile.name
}).success(function(data){
console.log(data);
}).error(function(err){
console.log(err);
});
And my sails.js controller method that handles the upload on the server starts like this:
upload: function (req, res) {
req.file('item-image').upload(function (err, files) {
if (err)
return res.serverError(err);
if(!files.length)
return res.serverError('No files received for upload.');
var file = files[0];
...
}
...
}
However, while the server function is being called, and the json data on the body exists, no files are being found by req.file('no matter what put here') callback.
Thanks in advance.
Upvotes: 2
Views: 1762
Reputation: 309
one important thing, if you want to process more than one file in your backend using:
req.file('files').upload({...});
you need to add the arrayKey: ''
parameter in your Upload.upload({})
like this:
Upload.upload({
url: 'http://localhost:1337/uploads',
arrayKey: '',
data: {
files: files
}
Upvotes: 0
Reputation: 24948
The argument to req.file
needs to be the name of the field in the request where Sails should look for the uploaded files. If you're doing a simple HTML form with something like:
<input type="file" name="myFileField" />
then in your controller code you would have:
req.file('myFileField').upload(...);
With uploader widgets like the ng-file-upload widget referenced in this question, it can sometimes be a little tricky to figure out what that field name is. In this case it's hidden in the usage instructions:
//fileFormDataName: myFile, // or a list of names for multiple files (html5). // Default is 'file'
So you can set fileFormDataName
to change the upload field name, or else it defaults to file
.
If you can't find the field name in the docs or by inspecting the HTML, the easiest thing to do is just do an upload (even if it's unsuccessful) and inspect the network request using the developer tools in Chrome:
This is from the Angular file upload demo page. You can see in the lower right where it says name="myFile"
; that's what you're looking for. In this case the file field is called myFile
.
Upvotes: 7