Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uploading file with jQuery Ajax

I have made many search on how to upload files from a form with Ajax, and found out that xhr2 should be able to do it. Yet, I have tried myself to use FormData objects and it doesn't work.

Here's a simple html form

<!DOCTYPE html>
<html>
    <head>
        <title>File Upload</title>
    </head>
    <body>
        <form id="form" method="post" action="post.php" enctype="multipart/form-data">
            <input type="file" name="img"/>
            <input type="submit" value="Upload" />
        </form>
        <script src="jquery.js"></script>
        <script src="upload.js"></script>
    </body>
</html>

And here's the 'post.php' file which works just fine when called the 'old-fashioned' way :

<?php
if($_FILES['img']['error'] > 0) die('Error ' . $_FILES['file']['error']);
if(empty($_FILES['img']['name'])) die('No file sent.');

$tmp = $_FILES['img']['tmp_name'];

if(is_uploaded_file($tmp))
{
    if(!move_uploaded_file($tmp, 'img.png')) echo 'error !';
}
else echo 'Upload failed !';
?>

And here's 'upload.js'

$(function() {
    $('#form').submit(function(e) {
        e.preventDefault();
        data = new FormData($('#form'));
        console.log('Submitting');
        $.ajax({
            type: 'POST',
            url: 'post.php',
            data: data,
            cache: false,
            contentType: false,
            processData: false
        }).done(function(data) {
            console.log(data);
        }).fail(function(jqXHR,status, errorThrown) {
            console.log(errorThrown);
            console.log(jqXHR.responseText);
            console.log(jqXHR.status);
        });
    });
});

Do you have any idea why it isn't working ? The console return 'No file sent'.

Thanks a lot !

like image 903
Théo Winterhalter Avatar asked Aug 25 '13 12:08

Théo Winterhalter


1 Answers

Try to replace the code:

data = new FormData($('#form'));

with this:

data = new FormData($('#form')[0]);

to get the first DOM element from the jQuery array.

like image 194
noamtcohen Avatar answered Sep 19 '22 12:09

noamtcohen