显示多文件上传 Jquery/Ajax 的进度 [英] Show a progress on multiple file upload Jquery/Ajax

查看:24
本文介绍了显示多文件上传 Jquery/Ajax 的进度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有上传表单,允许用户上传多个文件.我决定如果文件很大,进度条会很好.下面是我的源代码.我通常是 jquery 的新手,我只会使用 php,但我发现 ajax 对用户更友好.

<div class="close_btn"></div><div id="上传"></div><form action="global.func/file_upload.php" method="post" enctype="multipart/form-data" id="upload_file"><fieldset><legend>上传图片或视频</legend><input type="file" id="file" name="file[]" placeholder="上传图片或视频"多个/><input type="submit" value="上传文件" id="upload_file_btn" 需要/></fieldset><div class="bar"><div class="bar_fill" id="pb"><div class="bar_fill_text" id="pt"></div>

</表单>

<脚本>功能 OnProgress(事件,位置,总计,百分比完成){//进度条控制台日志(总计);$('#pb').width(percentComplete + '%')//更新进度条完成百分比$('#pt').html(percentComplete + '%');//更新状态文本}函数 beforeSubmit(){console.log('ajax 开始');}功能后成功(数据){控制台日志(数据);}$(document).ready(function(e) {$('#upload_file').提交(函数(事件){event.preventDefault();var filedata = document.getElementById("file");表单数据 = 新表单数据();var i = 0, len = filedata.files.length, 文件;for (i; i

图片上传工作正常,数组发送到ajax但进度条不动.事实上,调用的两个函数的 console.log 也不会出现.是否有正确的方法来调用我的 ajax 请求中的函数,以使此进度条正常工作.

<块引用>

beforeSubmit: beforeSubmit,上传进度:OnProgress,成功:成功后,

请注意,当控制台显示我的数据时,此函数 'success: afterSuccess' 正在工作.

解决方案

This is your HTML form

<input hidden="true" id="fileupload" type="file" name="image[]" 多个><div id ="divleft"><button id="btnupload"></button>

</表单>

这是您的 JQuery 和 ajax.默认情况下,fileInput 是隐藏的.

点击上传按钮

$("#btnupload").click(function(e) {$("#fileupload").click();e.preventDefault();});$('#fileupload').change(function (e) {$("#imageuploadform").submit();e.preventDefault();});$('#imageuploadform').submit(function(e) {var formData = new FormData(this);$.ajax({类型:'POST',网址:'ajax/上传图片',数据:表单数据,xhr:函数(){var myXhr = $.ajaxSettings.xhr();如果(myXhr.upload){myXhr.upload.addEventListener('progress',progress, false);}返回 myXhr;},缓存:假,内容类型:假,过程数据:假,成功:功能(数据){控制台日志(数据);alert('数据返回成功');},错误:函数(数据){控制台日志(数据);}});e.preventDefault();});功能进度(e){if(e.lengthComputable){var max = e.total;无功电流 = e.loaded;var百分比=(当前* 100)/最大;控制台日志(百分比);如果(百分比 >= 100){//处理完成}}}

你的php代码是这样的

$path);$filename = "image_" .$日期."_" .$uid ..".$ext;$this->createthumb($i,$filename);//将上传的文件从临时文件移动到上传目录if (move_uploaded_file($_FILES['image']['tmp_name'][$i], $path)){//$status = '图片上传成功!';//这里执行sql更新}别的 {$status = '上传失败:发生未知错误!';}}别的 {$status = '上传失败:文件格式不支持或太大无法上传!';}}别的 {$status = '上传失败:文件未上传!';}}}别的 {$status = '错误请求!';}回声 json_encode($json);?>

I have upload form that allows users to upload multiple files. I decided that a progress bar would be good if the files are quite large. Below is my source code. I am new to jquery normally I would just php but I find that ajax is more user friendly.

<div id="new_upload">
    <div class="close_btn"></div>
    <div id="uploads"></div>
    <form action="global.func/file_upload.php" method="post" enctype="multipart/form-data" id="upload_file">
    <fieldset><legend>Upload an image or video</legend>
    <input type="file" id="file" name="file[]" placeholder="Upload Image or Video" multiple /><input type="submit" value="upload file" id="upload_file_btn" required />
    </fieldset>

    <div class="bar">
        <div class="bar_fill" id="pb">
            <div class="bar_fill_text" id="pt"></div>
        </div>
    </div>

    </form>
</div>
<script>
function OnProgress(event, position, total, percentComplete){    
    //Progress bar
    console.log(total);
    $('#pb').width(percentComplete + '%') //update progressbar percent complete
    $('#pt').html(percentComplete + '%'); //update status text
}
function beforeSubmit(){
    console.log('ajax start');
}
function afterSuccess(data){
    console.log(data);
}
$(document).ready(function(e) {
    $('#upload_file').submit(function(event){
        event.preventDefault();
        var filedata = document.getElementById("file");
        formdata = new FormData();
        var i = 0, len = filedata.files.length, file;
         for (i; i < len; i++) {
            file = filedata.files[i];
            formdata.append("file[]", file);
        }
        formdata.append("json",true);
        $.ajax({
            url: "global.func/file_upload.php",
            type: "POST",
            data: formdata,
            processData: false,
            contentType: false,
            dataType:"JSON",
            xhr: function() {
                var myXhr = $.ajaxSettings.xhr();
                return myXhr;
            },
            beforeSubmit: beforeSubmit,
            uploadProgress:OnProgress, 
            success: afterSuccess,
            resetForm: true
        });
    });
});
</script>

The image upload works fine, the array send to ajax but the progress bar doesn't move. In fact the console.log for the two functions called need to produce this don't appear either. Is there a correct way to call the functions in my ajax request that would get this progress bar to work.

beforeSubmit: beforeSubmit, uploadProgress:OnProgress, success: afterSuccess,

NOTE that this function 'success: afterSuccess' is working as the console is displaying my data.

解决方案

This is your HTML form

<form method="post" action="uploadImages.php" name ='photo' id='imageuploadform' enctype="multipart/form-data">
        <input hidden="true" id="fileupload" type="file" name="image[]" multiple >

        <div id ="divleft">
            <button id="btnupload"></button>

        </div>    

    </form>

This is your JQuery and ajax. By default the fileInput is hidden.

Upload Button clicked

$("#btnupload").click(function(e) {

    $("#fileupload").click();
    e.preventDefault();

});


$('#fileupload').change(function (e) {

    $("#imageuploadform").submit();
    e.preventDefault();

});

$('#imageuploadform').submit(function(e) {

    var formData = new FormData(this);

    $.ajax({
        type:'POST',
        url: 'ajax/uploadImages',
        data:formData,
        xhr: function() {
                var myXhr = $.ajaxSettings.xhr();
                if(myXhr.upload){
                    myXhr.upload.addEventListener('progress',progress, false);
                }
                return myXhr;
        },
        cache:false,
        contentType: false,
        processData: false,

        success:function(data){
            console.log(data);

          alert('data returned successfully');

        },

        error: function(data){
            console.log(data);
        }
    });

    e.preventDefault();

});


function progress(e){

    if(e.lengthComputable){
        var max = e.total;
        var current = e.loaded;

        var Percentage = (current * 100)/max;
        console.log(Percentage);


        if(Percentage >= 100)
        {
           // process completed  
        }
    }  
 }

Your php code looks like this

<?php

header('Content-Type: application/json');

       $valid_exts = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
        $max_size = 30000 * 1024; // max file size in bytes

        $json = array();

            if ( $_SERVER['REQUEST_METHOD'] === 'POST' )
            {
                for($i=0;$i<count($_FILES['image']['tmp_name']);$i++)
                {
                    $path="image/uploads/photos/";

                    if(is_uploaded_file($_FILES['image']['tmp_name'][$i]) )
                    {
                      // get uploaded file extension
                      $ext = strtolower(pathinfo($_FILES['image']['name'][$i], PATHINFO_EXTENSION));
                      // looking for format and size validity
                          if (in_array($ext, $valid_exts) AND $_FILES['image']['size'][$i] < $max_size)
                          {
                                  // unique file path
                                  $uid = uniqid();
                                  $date = date('Y-m-d-H-i-s');
                                  $path = $path ."image_" .$date. '_' . $uid . "." .$ext;

                                  $returnJson[]= array("filepath"=>$path);

                                  $filename = "image_" . $date . "_" .$uid . "." . $ext;
                                  $this->createthumb($i,$filename);

                                    // move uploaded file from temp to uploads directory
                                  if (move_uploaded_file($_FILES['image']['tmp_name'][$i], $path))
                                  {
                                    //$status = 'Image successfully uploaded!';
                                      //perform sql updates here

                                  }
                                  else {
                                    $status = 'Upload Fail: Unknown error occurred!';
                                  }


                          }
                          else {
                            $status = 'Upload Fail: Unsupported file format or It is too large to upload!';
                          }
                    }
                    else {
                      $status = 'Upload Fail: File not uploaded!';
                    }
                }
              }
            else {
              $status = 'Bad request!';
            }


            echo json_encode($json);

?>

这篇关于显示多文件上传 Jquery/Ajax 的进度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆