SirDemon SirDemon - 4 years ago 879
Javascript Question

Uploading a file with ng-file-upload directive to a sails.js server

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.

Answer Source

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:

enter image description here

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download