Search code examples
restangularjspostfile-uploadngresource

Angularjs ngResource needs to have file as one of the fields


I have resource that has following fields:

description, picture

Is it possible to send that resource to URL as multipart/form, and if so, how?

I've tried putting:

app.factory('resource_name', ['$resource', function($resource) {
return $resource('<url> ',
    {
            <params_for_url>
    },
        save: {
            method: "POST",
            headers: {
                "Content-Type": "multipart/form-data;"
            }
        },

but this doesn't get to the server as form-data. It goes like JSON with header just set:

{
description: "gtrdgf",
picture: {
    lastModifiedDate:2013-11-26T20:42:13.000Z,
    name: "suggested_pokes.png"
    size: 32995
    type: "image/png"
    webkitRelativePath: ""
}

Did anyone met this requirement before? If this is possible at all...

Thanks!


Solution

  • I found solution for this one. You have to use FormData to submit it. You can use it as interceptor. I used it like this (this is my save method of ngResource)

                save: {
                    method: 'POST',
                    transformRequest: formDataObject,
                    headers: {'Content-Type':undefined, enctype:'multipart/form-data'}
                },
    

    and here is transformer:

            function formDataObject (data) {
                var fd = new FormData();
                angular.forEach(data, function(value, key) {
                    fd.append(key, value);
                });
                return fd;
            }