PHP+Ajax实现上传文件进度条动态显示进度功能

说个前提:PHP配置文件中规定默认上传文件大小限制2M以下,如需上传大文件需同时更改php.ini中的upload_max_filesizemax_execution_time以及post_max_size的值。

主界面以及Ajax实现:index.html

?

1

2

3

4

5

6

7

扫描二维码关注公众号,回复: 5362086 查看本文章

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

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

<!DOCTYPE html>

<html lang="en">

<head>

  <meta charset="UTF-8">

  <title>上传文件</title>

  <script type="text/javascript">

    function sub() {

      var obj = new XMLHttpRequest();

      obj.onreadystatechange = function() {

        if (obj.status == 200 && obj.readyState == 4) {

          document.getElementById('con').innerHTML = obj.responseText;

        }

      }

      // 通过Ajax对象的upload属性的onprogress事件感知当前文件上传状态

      obj.upload.onprogress = function(evt) {

        // 上传附件大小的百分比

        var per = Math.floor((evt.loaded / evt.total) * 100) + "%";

        // 当上传文件时显示进度条

        document.getElementById('parent').style.display = 'block';

        // 通过上传百分比设置进度条样式的宽度

        document.getElementById('son').style.width = per;

        // 在进度条上显示上传的进度值

        document.getElementById('son').innerHTML = per;

      }

      // 通过FormData收集零散的文件上传信息

      var fm = document.getElementById('userfile3').files[0];

      var fd = new FormData();

      fd.append('userfile', fm);

      obj.open("post", "upload.php");

      obj.send(fd);

    }

  </script>

  <style type="text/css">

    #parent {

      width: 200px;

      height: 20px;

      border: 2px solid gray;

      background: lightgray;

      display: none;

    }

    #son {

      width: 0;

      height: 100%;

      background: lightgreen;

      text-align: center;

    }

  </style>

</head>

<body>

  <h2>Ajax实现进度条文件上传</h2>

  <div id="parent">

    <div id="son"></div>

  </div>

  <p id="con"></p>

  <input type="file" name="userfile" id="userfile3"><br><br>

  <input type="button" name="btn" value="文件上传" onclick="sub()">

</body>

</html>

php处理上传文件:upload.php

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

<?php 

  // 上传文件进行简单错误过滤

  if ($_FILES['userfile']['error'] > 0) {

    exit("上传文件有错".$_FILES['userfile']['error']);

  }

  // 定义存放上传文件的真实路径

  $path = './upload/';

  // 定义存放上传文件的真实路径名字

  $name = $_FILES['userfile']['name'];

  // 将文件的名字的字符编码从UTF-8转成GB2312

  $name = iconv("UTF-8", "GB2312", $name);

  // 将上传文件移动到指定目录文件中

  if (move_uploaded_file($_FILES['userfile']['tmp_name'], $path.$name)) {

    echo "文件上传成功";

  } else {

    echo "文件上传失败";

  }

 ?>

原文链接:https://www.jb51.net/article/141412.htm

猜你喜欢

转载自blog.csdn.net/u010433704/article/details/86646198