ajax 多文件上传

接着上篇

要想实现多文件上传,非常简单,首先给文件域添加一个 multiple 属性

<input id="fileupload" type="file" name="file" style="display: none;" multiple>

然后修改PHP 代码

<?php
$file=$_FILES['file'];
// 获取文件扩展名
$res=pathinfo($file['name']);
$exname=$res['extension'];
// 生成唯一的名字
$filename=time().mt_rand().'.'.$exname;

move_uploaded_file($file['tmp_name'],'./upload/'.$filename);
echo json_encode(['url'=>'upload/'.$filename]);

修改的重点在于如下这行代码

// 生成唯一的名字
$filename=time().mt_rand().'.'.$exname;

因为是在本地测试,如果选择的多个文件都比较小,如果只使用 time() 生成的时间戳作为文件名字,就会造成两个文件可能重名,后面文件会覆盖前面文件的情况,所以又加了一个随机数,组合在一起作为文件名称

最后附上完整的html代码和php代码

html 代码

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <link href="https://cdn.bootcss.com/twitter-bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet">
  <style>
    .box {
      width: 500px;
      padding: 10px;
      margin: 50px auto;
    }

    .upload {
      width: 100px;
      font-size: 20px;
    }

    .progress_box {
      margin-top: 10px;
      display: none;
    }
  </style>
</head>

<body>
  <div class="box">
    <label for="fileupload" class="upload btn btn-success glyphicon glyphicon-upload">上传</label>
    <input id="fileupload" type="file" name="file" style="display: none;" multiple>
    <!--上传进度条-->
    <div class="progress_box">
      <progress value="0" max="100"></progress>
      <span id="upload_info"></span>
    </div>
    <!--图片上传成功后预览-->
    <img id="uploadimg" src="" width="400px" />
  </div>
</body>

</html>
<script src="./jQuery-File-Upload-10.4.0/js/jquery-3.4.1.min.js"></script>
<script src="./jQuery-File-Upload-10.4.0/js/vendor/jquery.ui.widget.js"></script>
<script src="./jQuery-File-Upload-10.4.0/js/jquery.iframe-transport.js"></script>
<script src="./jQuery-File-Upload-10.4.0/js/jquery.fileupload.js"></script>

<script>
  $('#fileupload').fileupload({
    dataType: 'json',
    url: "handle_upload1.php",//处理上传的php文件地址
    //设置进度条
    progressall: function (e, data) {
      var progress = parseInt(data.loaded / data.total * 100);
      $('progress').val(progress);
    },
    //上传完成之后的操作,显示在img里面
    done: function (e, data) {
      // 如果上传的图片,就取消下面代码的注释
      //$("#uploadimg").attr('src', data.result.url);
      $('#upload_info').html('上传完成')
    }
  })
  // 用户再次选择文件后,清除提示文字
  $('#fileupload').on('fileuploadadd', function () {    
    $('.progress_box').css('display', 'block')
    $('#upload_info').html('')
  })

</script>

PHP 代码

<?php
$file=$_FILES['file'];
// 获取文件扩展名
$res=pathinfo($file['name']);
$exname=$res['extension'];
// 生成唯一的名字
$filename=time().mt_rand().'.'.$exname;

move_uploaded_file($file['tmp_name'],'./upload/'.$filename);
echo json_encode(['url'=>'upload/'.$filename]);
发布了138 篇原创文章 · 获赞 51 · 访问量 33万+

猜你喜欢

转载自blog.csdn.net/mynewdays/article/details/103281995