2014-04-22 18 views
11

Tôi có biểu mẫu tải lên cho phép người dùng tải lên nhiều tệp. Tôi quyết định rằng một thanh tiến trình sẽ là tốt nếu các tập tin là khá lớn. Dưới đây là mã nguồn của tôi. Tôi mới đến jquery bình thường tôi sẽ chỉ php nhưng tôi thấy rằng ajax thân thiện với người dùng hơn.Hiển thị tiến trình tải lên nhiều tệp Jquery/Ajax

<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> 

Tải lên hình ảnh hoạt động tốt, mảng gửi đến ajax nhưng thanh tiến trình không di chuyển. Trong thực tế, console.log cho hai chức năng được gọi là cần phải tạo ra điều này cũng không xuất hiện. Có một cách chính xác để gọi các chức năng trong yêu cầu ajax của tôi mà sẽ nhận được thanh tiến trình này để làm việc.

beforeSubmit: beforeSubmit, uploadProgress: OnProgress, thành công: afterSuccess,

Chú ý rằng chức năng này 'thành công: afterSuccess' đang làm việc như giao diện điều khiển được hiển thị dữ liệu của tôi.

+0

Tại sao bạn không kiểm tra câu trả lời Eskinder không? Nó có vẻ hoàn thiện hơn với tôi. – Adam

Trả lời

63

Đây là hình thức HTML của bạn

<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> 

Đây là JQuery và ajax của bạn. Theo mặc định, tệp tinInput bị ẩn.

Tải lên nút nhấp

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

mã php của bạn trông như thế này

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

?> 
+3

Đây là ví dụ hoàn hảo về cách thực hiện điều này. – Hobbes

+2

Khi thử nghiệm localhost này, tôi chỉ nhận được 100% sự kiện. Tải lên cục bộ tự nhiên cực kỳ nhanh. Điều tiết mạng để xem các sự kiện gia tăng. – Gunslinger

+0

Giống như @Gunslinger nhưng tôi đang gửi tới máy chủ từ xa. Sử dụng các tập tin từ 5MB trở lên gọi tiến độ ngay lập tức và chính xác như mong đợi. Tuy nhiên, việc sử dụng các tệp nhỏ (er) khoảng 2MB không bao giờ gọi tiến trình. Chỉ đơn giản là khoảng 10 giây chậm trễ và sau đó tiến trình được gọi với 100 ... – rick6

3

Bạn phải sử dụng XMLHttpRequest tùy chỉnh để thực hiện việc này với AJAX và jQuery. Có một ví dụ ở đây: How can I upload files asynchronously?

+0

Hàm xhr:() thay vì uploadprogress xử lý này, thnkyou –

Các vấn đề liên quan