Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 505
Slaven Tomac Avatar asked Nov 26 '13 21:11

Slaven Tomac


1 Answers

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;
        }
like image 188
Slaven Tomac Avatar answered Oct 03 '22 01:10

Slaven Tomac