Upload nhiều file bằng Ajax kết hợp Progress Bar phần 2

Tiếp theo chúng ta sẽ thực hiện viết code ajax upload của lugin ajaxForm:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<script>
  var progressbar = $('#progressbar');
  var percent = $('#percent');
  var result = $('#result');
  var percentValue = "0%";
 
  $('#form_upload_ajax').ajaxForm({
      // Do something before uploading
      beforeUpload: function() {
        result.empty();
        percentValue = "0%";
        progressbar.width = percentValue;
        percent.html(percentValue);
      },
     
      // Do somthing while uploading
      uploadProgress: function(event, position, total, percentComplete) {
        var percentValue = percentComplete + '%';
        progressbar.width(percentValue)
        percent.html(percentValue);
      },
     
      // Do something while uploading file finish
      success: function() {
        var percentValue = '100%';
        progressbar.width(percentValue)
        percent.html(percentValue);
      },
     
      // Add response text to div #result when uploading complete
      complete: function(xhr) {    
        $('#result').html(xhr.responseText);
      }
  });
</script>
– Công việc cuối cùng của chúng ta là viết code php xử lý việc upload nhiều file,file upload.php với nội dung:

1
2
3
4
5
6
7
8
9
10
11
<?php
//lưu biến môi trường khi thực hiện upload
$file  = $_FILES['img'];
$count = count($file['name']);//lấy tổng số file được upload
for($i=0; $i<=$count-1; $i++) {

     move_uploaded_file($_FILES['img']['tmp_name'][$i],"upload/".$_FILES['img']['name'][$i]);
     $url  = "upload/".$_FILES['img']['name'][$i];
     echo "<img src='".$url."' /><br/>";
}
?>
– Và kết quả demo sẽ như sau:


You can see more php tutorial at: http://iphptutorial.blogspot.com/
Share on Google Plus

About Unknown

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 nhận xét:

Đăng nhận xét