andrescabana86
andrescabana86

Reputation: 1788

upload file with a form via ajax nodejs express

this is the ajax file

$(form).submit(function()
            {
                $.ajax(
                {
                    url:'/newProduct',
                    cache: false,
                    type: 'POST',
                    data: $(form).serialize(),
                    success:function(datos)
                    {
                        console.dir(datos)
                    },
                    error:function(xhr,tm)
                    {

                    },
                    complete:function()
                    {
                        form.reset();

                    }
                })
return false        

            });

this on the server

exports.newProduct=function(req,res)
{
    console.dir(req.body)
    console.dir(req.files)
    return res.send('Producto Cargado correctamente.');
}

the file didnt upload, the info on server shows nothing, nothing happends

Upvotes: 2

Views: 8357

Answers (2)

Alon Valadji
Alon Valadji

Reputation: 628

only with html5 formData object and you need to append files to it manually:

New Tricks in XMLHttpRequest2

uploading files with ajax

you can use jQuery nice plugin like with fallback etc.:

jQuery File Upload

Upvotes: 1

Femi
Femi

Reputation: 64700

You can't (as far as I understand it) use $.ajax to perform a multipart/form-data form submission (not without manually building the POST body). The Express file upload requires that your HTML <form> element have the enctype="multipart/form-data" attribute set. Do you have it set?

For what you're trying to do you probably want to use a hidden iframe to perform the post, then have the server return a javascript snippet that calls back with success/failure. There are a number of jQuery plugins that do this for you (jQuery Form does it, I believe).

Upvotes: 3

Related Questions