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
265 views
in Technique[技术] by (71.8m points)

php - upload file through ajax

I use 2 file index.js, upload.php try to upload file(img) through ajax and if success append to div uploadfile_show.
but it doesn't work , have few question and below is my code any suggestion?

Thanks.

upload.php
1. form enctype still need to add?
2. if($_FILES) and check $_FILES size or tmp_name still use $_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
3. this few line is it the right?
var uf = $('.uploaddiv form');var fd = new FormData(uf);fd.append('uploadfile', uploadfile);
data: fd,
4. any thing I missed or wrong?

$('.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);
        }
    });
});
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

FormData takes a form element in its constructor not a jQuery object, also as you are using ajax to submit the form you'll have to prevent its default action(i.e. submitting) by calling 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);
        }
    });
});

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

...