Angularjs ngResource needs to have file as one of the fields
Asked Answered
H

1

5

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!

Holsworth answered 26/11, 2013 at 21:48 Comment(1)
just setting content type won't upload file using AJAX....use a file uploader plugin if want cross browser supportOpuscule
H
11

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;
        }
Holsworth answered 1/10, 2014 at 13:5 Comment(5)
what is the transformer is it required?Budd
otherwise it didn't send the file...it just sent simple form fields. and what transformer is, look at official angularjs pagesHolsworth
This works but the header Content-length is not being set for me when using this, is there a way to set that as well for a file?Carbo
Have you tried this with a form that doesn't contain a File? Does it work?Neibart
I think it should, but in that case you should also think about changing enctypeHolsworth

© 2022 - 2024 — McMap. All rights reserved.