通过ajax上传文件

时间:2013-01-24 06:35:44

标签: php jquery ajax

我使用2个文件index.js,upload.php尝试通过ajax上传文件(img),如果成功附加到div uploadfile_show
但它不起作用,几乎没有问题,下面是我的代码有什么建议吗?

感谢。

upload.php的
1. form enctype仍然需要添加?
2. if($_FILES)并检查$ _FILES大小或tmp_name是否还使用$_FILES

if($_FILES){
    $filename = $_FILES['uploadfile']['name'];
    $filetmp = $_FILES['uploadfile']['tmp_name'];
    $filesize = $_FILES['uploadfile']['size'];
    if($filesize < 1000000){
        move_uploaded_file($filetmp,'upload/tmp/'.$filename);
        print"
            upload success
            <img src=\"upload/tmp/$filename\">
        ";
    }
    else{
    }
}
else{
    print"
        <div class=\"uploaddiv\">
            <form enctype=\"multipart/form_data\">
                <input type=\"type\" name=\"uploadfile\">
                <input type=\"submit\" value=\"upload\" class=\"btn\">
            </form>
        </div>
    ";
}
print"
    <div class=\"uploadfile_show\"></div>
";

index.js
这几行是对的吗? var uf = $('.uploaddiv form');var fd = new FormData(uf);fd.append('uploadfile', uploadfile);
data: fd,
4.我错过了什么或错了什么?

$('.btn').click(function(){
    var uf = $('.uploaddiv form');
    var fd = new FormData(uf);
    fd.append('uploadfile', uploadfile);
    $.ajax({
        type: "POST",
        url: "upload.php",
        data: fd,
        processData:false,
        contentType: false,
        success: function(html){
            $('.uploadfile_show').append(html);
        }
    });
});

1 个答案:

答案 0 :(得分:2)

FormData在其构造函数中使用表单元素而不是jQuery对象,同样,当您使用ajax提交表单时,您必须通过调用preventDefault()来阻止其默认操作(即提交)

$('.btn').click(function(e){
    e.preventDefault();
    var uf = $('.uploaddiv form');
    var fd = new FormData(uf[0]);
    $.ajax({
        type: "POST",
        url: "upload.php",
        data: fd,
        processData:false,
        contentType: false,
        success: function(html){
            $('.uploadfile_show').append(html);
        }
    });
});