Gesiel da Silva Gesiel da Silva - 6 months ago 21
AngularJS Question

Multipart requests with Angular

So, i'm trying to post a multipart request with angular and the request payload dont match with my expectations.
What i'm doing:

function sendBroadcastImage(ids, img) {
var fd = new FormData();
fd.append('destinationUsersIds', angular.toJson({
values : ids
}));
fd.append('file', img);

$http.post(
'/some/api/url/',
fd,
{
transformRequest: angular.identity,
headers: { 'Content-Type': undefined }
});
}


I get this payload:

------WebKitFormBoundary3KBBZ9GEkqoGGQMC
Content-Disposition: form-data; name="destinationUsersIds"

{"values":[2235]}
------WebKitFormBoundary3KBBZ9GEkqoGGQMC
Content-Disposition: form-data; name="file"; filename="capacete.jpg"
Content-Type: image/jpeg


------WebKitFormBoundary3KBBZ9GEkqoGGQMC--


What payload I need (with content-type for the first boundary too):

------WebKitFormBoundary3KBBZ9GEkqoGGQMC
Content-Disposition: form-data; name="destinationUsersIds"
Content-Type: application/json

{"values":[2235]}
------WebKitFormBoundary3KBBZ9GEkqoGGQMC
Content-Disposition: form-data; name="file"; filename="capacete.jpg"
Content-Type: image/jpeg


------WebKitFormBoundary3KBBZ9GEkqoGGQMC--


Is it possible? How can I do it?

Answer

According to this guy and documentation of FormData, u can use Blob to append a field with specific content type.

var fd = new FormData();
formData.append('destinationUsersIds', new Blob([angular.toJson({
    values: ids
})], {
    type: "application/json"
}));

Let me know if this works for you.