如何知道do_upload是否已经启动并完成?

时间:2016-08-01 02:11:28

标签: javascript php jquery codeigniter

我正在使用CodeIgniter,我创建了一个用户可以上传视频的表单。我想创建一个进度条,向用户显示其仍在上传,并在上传完成后隐藏它。我想要做的是当点击提交按钮时它将调用我的加载gif,我希望它继续加载,直到上传完成。如何检测上传是否完成?

CSS

<?php echo form_open_multipart('video_controller/video_form');?>

<div class="form-group">
        <label for="title">Video</label>
        <input type="file" accept=".mp4" class="form-control" name="video_field" placeholder="Video"></input>
</div>

<button class="btn btn-success pull-right" type="submit" value="upload" id="btn-submit">Create</button> 

 <?php echo form_close();?>

CodeIgniter

public function video_form(){
   if (empty($_FILES['video_field']['name'])){
        $this->form_validation->set_rules('video_file', 'Video File', 'required');
    }

   if($this->form_validation->run() == FALSE){
    .....
   }else{
      $uploaderror = "";
      $video_info = $this->upload_videos();

     ..... 
     Insert query code here 
     .....
   }
}
private function upload_videos(){

    $config = array();
    $config['upload_path']          = './uploads/videos/';
    $config['allowed_types']        = 'mp4';

    $this->load->library('upload', $config);
    $this->upload->initialize($config);

    if ( ! $this->upload->do_upload('video_field'))
    {
        $error_msg = $this->upload->display_errors('','');
        error_log('UPLOAD ERROR: '.$error_msg);
        if($error_msg!='You did not select a file to upload.'){
            $filename = array('error' =>$error_msg.'('. $this->input->post('video_field') .')');
        }
    }
    else
    {
        $vid = $this->upload->data();
        $filename = array('video_field' =>$vid['file_name']);
    }

    return $filename;
}

2 个答案:

答案 0 :(得分:0)

您可以使用change事件,XMLHttpRequest.upload.progress事件

HTML

<input type="file" /><progress min="0" max="0" value="0"></progress>

的javascript

var progress = $("progress");
$(":file").change(function(e) {
  var file = e.target.files[0];
  progress.val(0);
  var request = new XMLHttpRequest();
  if (request.upload) {
    request.upload.onprogress = function(event) {
      if (progress.val() == 0) {
        progress.attr("max", event.total)
      }
      if (event.lengthComputable) {
        // show `.gif` or update `progress` value here
        // if `event.loaded` === `event.total` 
        // set `.gif` `display` to `none`
        console.log(event.loaded, event.total);
        progress.val(event.loaded)
      }
    }
    request.onload = function() {
      // do stuff with response
    }
  };
  request.open("POST", "/path/to/server/");
  request.send(file)
});

jsfiddle https://jsfiddle.net/576wrxLg/

答案 1 :(得分:0)

我在我的codeigniter项目中使用JS中的代码做了同样的事情。 我百分百肯定这对你有用。 :)

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

    var formData = new FormData(this);

    $.ajax({
        type:'POST',
        url: base_url + "student/importAjax",
        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,
        dataType : "json",
        success: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);
        $('#progress-bar').css('width',Percentage+'%');
        $('.sr-only').html(Percentage+'%');
        if(Percentage >= 100)
        {
           // process completed  
        }
    }  
 }

这是我的观点(Bootstrap主题)

 <form name="importForm" id="importForm" enctype="multipart/form-data"> 
                <?php //echo form_open_multipart('admin/upload/do_upload'); ?>


                <div class="box-body">
                    <div class="form-group">
                        <label for="exampleInputFile">Select File</label>
                        <input type="file" id="importInputFile" name="importInputFile" />
                        <p class="help-block">.xls / xlsx </p>
                    </div>
                    <div class="form-group">
                        <input type="checkbox" name="mid_term" class="check"><label style="margin-left: 10px;"> Mid Term User</label>
                    </div>

                    <div class="progress progress-sm active">
                        <div style="width:0%" aria-valuemax="100" aria-valuemin="0" aria-valuenow="20" role="progressbar" id="progress-bar" class="progress-bar progress-bar-success progress-bar-striped">
                            <span class="sr-only"></span>
                        </div>
                    </div>



                    <div class="box-footer">
                        <button class="btn btn-primary" id="ajaxImportUpload" type="submit">Submit</button>
                    </div>
                </div>
            </form>

我的控制器

public function importAjax() {

        $upload_path = './uploads/';
        $newname = rand(0000, 9999) . basename($_FILES["importInputFile"]["name"]);
        $target_file = $upload_path . $newname;

        $filename = $newname;
        $filenameArray = explode(".", $filename);
        $extension = end($filenameArray);
        if ($extension == 'xlsx' || $extension == 'xls') {
            if (move_uploaded_file($_FILES["importInputFile"]["tmp_name"], $target_file)) {
                // echo "The file ".$newname . " has been uploaded.";
            } else {
                //echo "Sorry, there was an error uploading your file.";
            }
            $this->load->library('Excel');
            $csvData = $this->excel->parseFile($target_file, false);
            $fileType = 'Excel';
        } else {
            echo json_encode(array('error' => true, 'msg' => 'xlsx and xls are allowed extnsion'));
            return false;
        }
        array_shift($csvData);
        $user = array();

        if (isset($_POST['mid_term']) && $_POST['mid_term'] == 'on') {
            $mid_term = 1;
        } else {
            $mid_term = 0;
        }

        $insertedCount=0;
        $totalCount=0;
        foreach ($csvData as $studentData) {
            $totalCount++;
            $id = $this->StudentModel->checkImportSchool($studentData[2]);
            $cid = $this->StudentModel->checkImportclass($studentData[7]);
            $sid = $this->StudentModel->checkImportStudentUsername($studentData[0]);

            if ($id > 0 && $sid=="notFound") {
                $fullname = explode(" ", $studentData[1]);
                if (isset($fullname[1]) == '')
                    $middlename = '';
                else
                    $middlename = $fullname[1];
                if (isset($fullname[2]) == '')
                    $lastname = '';
                else
                    $lastname = $fullname[2];

                $user['username'] = $studentData[0];
                $user['firstname'] = $fullname[0];
                $user['middlename'] = $middlename;
                $user['lastname'] = $lastname;
                $user['phone'] = $studentData[3];
                $user['email'] = $studentData[4];

                $password_salt = substr(sha1(uniqid(rand(), true)), 1, 20);
                $password = md5($studentData[5] . $password_salt);
                $parentPassword = md5($studentData[6] . $password_salt);

                $user['password'] = $password;
                $user['parentPassword'] = $parentPassword;
                $user['password_salt'] = $password_salt;
                $user['mid_term'] = $mid_term;
                $user['userType'] = 'student';
                $school = $id;
                $class = $cid;
                $this->StudentModel->importFromExcel($user, $class, $school);
                $insertedCount++;
            }
            else {
                    $skipData[]=$studentData;
            }
        }

        unlink($target_file);
        if(!empty($skipData)){
            $this->session->set_userdata(array('item'=>$skipData));    
        }
        else{
            $skipData=array();
        }
        $skipDataCount=count($skipData);
        echo json_encode(array('error' => false, 'msg' => 'Data Inserted Successfully','skipData'=>$skipData,'insertedCount'=>$insertedCount,'skipDataCount'=>$skipDataCount,'totalCount'=>$totalCount));
    }