Upload with $ http post

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 do you adapt it to upload images?

    
asked by anonymous 02.03.2015 / 20:46

2 answers

1

As you may have noticed, Angular by default does POST with Content-Type: application/json .

To change the behavior, it is necessary to construct a FormData and instruct Angular not to change the contents 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);
    });
};

Notice that in this code, besides the image, I also send a description of it. In other words, just like in a POST request without an Angular (such as the one generated by the browser in a form without Angular), you can send "non-binary" data, or even several images if you prefer.     

06.04.2015 / 06:38
0

There are several angular ready libraries for this, including:

I recommend that you review the options and choose the one that best fits your case.

    
05.03.2015 / 20:46