2016-08-01 97 views
0

我使用CodeIgniter,並創建了一個用戶可以上傳視頻的表單。我想創建一個進度條,以顯示用戶仍在上傳並在上傳完成後隱藏它。我想要做的是當提交按鈕是單擊它會調用我的加載gif,我希望它繼續加載,直到上傳完成。我如何檢測上傳是否完成?如何知道do_upload是否已經啓動並完成?

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();?> 

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; 
} 
+0

您使用的可能是jQuery函數有一個'.done'方法 –

+0

@JaromandaX我沒有使用'.done'方法,如何使用它? – natsumiyu

+0

如果你發佈了你的代碼,這會容易得多 –

回答

0

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

HTML

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

的java腳本

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/

+0

在'request.open()'中,我會將鏈接放在接下來的位置嗎? – natsumiyu

+0

@mori _「在'request.open()中,我會把鏈接放在哪裏?」_請參閱https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/open – guest271314

+0

當我點擊「選擇文件」按鈕選擇一個文件,然後在選擇要上傳的文件後點擊「打開」按鈕。 'progress'標籤將加載..但我沒有點擊提交按鈕來調用do_upload()..進度條是不是基於我的代碼點火器代碼中的do_upload()函數? – natsumiyu

0

我做我笨項目一樣,此代碼在JS .. 我100%肯定這會爲你工作。 :)

$('#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 
     } 
    } 
} 

,這是我的看法(引導主題)

<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)); 
    } 
+0

,控制器有代碼將圖像上傳到指定位置,並返回帶有json_encode()的數組成功/錯誤(如果是)。 –

+0

是'student/importAjax'是一個具有'do_upload'和插入查詢的Web服務嗎? – natsumiyu

+0

它不再保存和上傳:( – natsumiyu

相關問題