1
In my controller, I have the following code that I use to post my form:
$http.post(url, json_object).then(function (results) {
console.log(results.data);
});
The above code sends a json to the server.
How to adapt it to upload images?
1
In my controller, I have the following code that I use to post my form:
$http.post(url, json_object).then(function (results) {
console.log(results.data);
});
The above code sends a json to the server.
How to adapt it to upload images?
1
As you may have noticed, Angular by default makes POST with the Content-Type: application/json
.
To change the behavior, it is necessary to build a FormData
and instruct Angular not to change the content of the parameters sent in the POST request.
This can all be done with the following code:
// insira este código aonde for apropriado (controller, service, etc)
this.upload = function () {
var t = this; // preguiça de escrever this
var promise = null;
var form = new FormData();
form.append("image", t.image);
form.append("description", t.description);
promise = $http.post("/api/1/images", form, {
headers: {
"Content-Type": undefined // remove o content-type
},
transformRequest: angular.identity // não transforma os parâmetros
});
promise.success(function (data, status) {
alert("Uhuuulll!!!");
});
promise.error(function (data, status) {
alert("Wow =/ " + data);
});
};
Note that in this code, in addition to the image, I also send a description of it. That is, just like a POST request without Angular (just like the one generated by the browser in a form
without Angular), you can send "non-binary" data, or even multiple images, if you prefer.
0
There are several angular ready libraries for this, among them:
I recommend that you review the options and choose the one that best fits your case.
This search I did on google before creating the question. What I want is to adapt what I have and not use something ready, but thanks for the help.
Browser other questions tagged angularjs upload
You are not signed in. Login or sign up in order to post.
I am using a version of this library for file upload using $Resource: https://github.com/danialfarid/angular-file-upload
– OnoSendai