Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 !

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
274 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...