如何上传带进度条的文件?

时间:2016-05-24 11:27:50

标签: php jquery ajax file-upload

我有一个带有进度条的上传器:

index.php

<h1>Uploader</h1>
<hr>
<form action="#">
    <input type="file" name="image" >
    <button class="btn btn-sm btn-info upload" type="submit">Upload</button>
    <button type="button" class="btn btn-sm btn-danger cancel">Cancel</button>

    <div class="progress progress-striped active">
        <div class="progress-bar" style="width:0%"></div>
    </div>
</form>


<script>

    $(document).on('submit','form',function(e){
        e.preventDefault();

        $form = $(this);

        uploadImage($form);

    });

    function uploadImage($form){
        $form.find('.progress-bar').removeClass('progress-bar-success')
                                    .removeClass('progress-bar-danger');

        var formdata = new FormData($form[0]); //formelement
        var request = new XMLHttpRequest();

        //progress event...
        request.upload.addEventListener('progress',function(e){
            var percent = Math.round(e.loaded/e.total * 100);
            $form.find('.progress-bar').width(percent+'%').html(percent+'%');
        });

        //progress completed load event
        request.addEventListener('load',function(e){
            $form.find('.progress-bar').addClass('progress-bar-success').html('upload completed....');
        });

        request.open('post', 'upload.php');
        request.send(formdata);

        $form.on('click','.cancel',function(){
            request.abort();

            $form.find('.progress-bar')
                .addClass('progress-bar-danger')
                .removeClass('progress-bar-success')
                .html('upload aborted...');
        });

    }

</script>

upload.php

<?php

    $tmp_file = $_FILES['image']['tmp_name'];
    $filename = $_FILES['image']['name'];

    move_uploaded_file($tmp_file, 'files/'. $filename);

    echo "hello world";

?>

到目前为止,这项工作非常顺利。 但是在upload.php我希望继续做更多的事情。我只是尝试写hello world。但遗憾的是,我一直在index.php,我无法在任何地方看到hello world

0 个答案:

没有答案