Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
300 views
in Technique[技术] by (71.8m points)

php - 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 !

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...