简体   繁体   English

使用jQuery Ajax上传文件

[英]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. 我已经多次搜索如何使用Ajax从表单上传文件,并发现xhr2应该能够做到。 Yet, I have tried myself to use FormData objects and it doesn't work. 然而,我已经尝试使用FormData对象,但它不起作用。

Here's a simple html form 这是一个简单的html表单

<!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 : 这里是'post.php'文件,当称为'老式'方式时,它可以正常工作:

<?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' 这里是'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'. 控制台返回“No file sent”。

Thanks a lot ! 非常感谢 !

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. 从jQuery数组中获取第一个DOM元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM