Thursday 3 November 2016

AngularJS: how to implement a simple file upload with multipart form?



I want to do a simple multipart form post from AngularJS to a node.js server,
the form should contain a JSON object in one part and an image in the other part,
(I'm currently posting only the JSON object with $resource)




I figured I should start with input type="file", but then found out that AngularJS can't bind to that..



all the examples I can find are for wraping jQuery plugins for drag & drop. I want a simple upload of one file.



I'm new to AngularJS and don't feel comfortable at all with writing my own directives.


Answer



A real working solution with no other dependencies than angularjs (tested with v.1.0.6)



html







Angularjs (1.0.6) not support ng-model on "input-file" tags so you have to do it in a "native-way" that pass the all (eventually) selected files from the user.



controller



$scope.uploadFile = function(files) {
var fd = new FormData();

//Take the first selected file
fd.append("file", files[0]);

$http.post(uploadUrl, fd, {
withCredentials: true,
headers: {'Content-Type': undefined },
transformRequest: angular.identity
}).success( ...all right!... ).error( ..damn!... );

};



The cool part is the undefined content-type and the transformRequest: angular.identity that give at the $http the ability to choose the right "content-type" and manage the boundary needed when handling multipart data.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...