上传文件的jQuery阿贾克斯 [英] Uploading file with jQuery Ajax

查看:98
本文介绍了上传文件的jQuery阿贾克斯的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经对如何从使用Ajax表单上传文件许多搜索,并发现xhr2应该能够做到这一点。然而,我曾尝试自己使用FORMDATA对象和它不工作。

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.

下面是一个简单的HTML表单

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>

而这里的post.php中文件时,被称为老式方式,也工作得很好:

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 !';
?>

而这里的upload.js

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'.

非常感谢!

推荐答案

尝试更换code:

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

这一点:

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

从jQuery的数组中获得第一个DOM元素。

to get the first DOM element from the jQuery array.

这篇关于上传文件的jQuery阿贾克斯的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆