TP5框架实现一次选择多张图片并预览的方法示例


Posted in PHP onApril 04, 2020

本文实例讲述了TP5框架实现一次选择多张图片并预览的方法。分享给大家供大家参考,具体如下:

点击选择图片(可选多张),确定后将选择的图片显示在页面上,已经选择的图片也可以删除,点击提交将图片提交给后台。

1、效果图

TP5框架实现一次选择多张图片并预览的方法示例

2、code

用input标签并选择type=file,记得带上multiple,不然就只能单选图片了

如果不想通过 ajax 提交,一定要加上文件传输协议 ( enctype="multipart/form-data" )

view

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>showImages</title>
  <style type="text/css">
    .float{
      float:left;
      width : 200px;
      height: 200px;
      overflow: hidden;
      border: 1px solid #CCCCCC;
      border-radius: 10px;
      padding: 5px;
      margin: 5px;
    }
    img{
      position: relative;
    }
    .result{
      width: 200px;
      height: 200px;
      text-align: center;
      box-sizing: border-box;
    }
    #file_input{
      display: none;
    }
    .delete{
      width: 200px;
      height:200px;
      position: absolute;
      text-align: center;
      line-height: 200px;
      z-index: 10;
      font-size: 30px;
      background-color: rgba(255,255,255,0.8);
      color: #777;
      opacity: 0;
      transition-duration: :0.7s;
      -webkit-transition-duration: 0.7s;
    }
    .delete:hover{
      cursor: pointer;
      opacity: 1;
    }
  </style>
  <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
  <script type="text/javascript">
    window.onload = function(){
      var input = document.getElementById("file_input");
      var result;
      var dataArr = []; // 储存所选图片的结果(文件名和base64数据)
      var fd; //FormData方式发送请求
      var oSelect = document.getElementById("select");
      var oAdd = document.getElementById("add");
      var oSubmit = document.getElementById("submit");
      var oInput = document.getElementById("file_input");

      if(typeof FileReader==='undefined'){
        alert("抱歉,你的浏览器不支持 FileReader");
        input.setAttribute('disabled','disabled');
      }else{
        input.addEventListener('change',readFile,false);
      } //handler

      function readFile(){
        fd = new FormData();
        var iLen = this.files.length;
        var index = 0;
        for(var i=0;i<iLen;i++){
          if (!input['value'].match(/.jpg|.gif|.png|.jpeg|.bmp/i)){//判断上传文件格式
            return alert("上传的图片格式不正确,请重新选择");
          }
          var reader = new FileReader();
          reader.index = i;
          fd.append(i,this.files[i]);
          reader.readAsDataURL(this.files[i]); //转成base64
          reader.fileName = this.files[i].name;

          reader.onload = function(e){
            var imgMsg = {
              name : this.fileName,//获取文件名
              base64 : this.result  //reader.readAsDataURL方法执行完后,base64数据储存在reader.result里
            }
            dataArr.push(imgMsg);
            result = '<div class="delete">delete</div><div class="result"><img src="'+this.result+'" alt=""/></div>';
            var div = document.createElement('div');
            div.innerHTML = result;
            div['className'] = 'float';
            div['index'] = index;
            document.getElementsByTagName('body')[0].appendChild(div); //插入dom树
            var img = div.getElementsByTagName('img')[0];
            img.onload = function(){
              var nowHeight = ReSizePic(this); //设置图片大小
              this.parentNode.style.display = 'block';
              var oParent = this.parentNode;
              if(nowHeight){
                oParent.style.paddingTop = (oParent.offsetHeight - nowHeight)/2 + 'px';
              }
            }

            div.onclick = function(){
              this.remove();         // 在页面中删除该图片元素
              delete dataArr[this.index]; // 删除dataArr对应的数据

            }
            index++;
          }
        }
      }

      function send(){
        var submitArr = [];
        for (var i = 0; i < dataArr.length; i++) {
          if (dataArr[i]) {
            submitArr.push(dataArr[i]);
          }
        }
        // console.log('提交的数据:'+JSON.stringify(submitArr))
        $.ajax({
          url : 'http://39.106.182.218',
          type : 'post',
          data : JSON.stringify(submitArr),
          dataType: 'json',
          //processData: false,  用FormData传fd时需有这两项
          //contentType: false,
          success : function(data){
            console.log('返回的数据:'+JSON.stringify(data))
          }

        })
      }

      oSelect.οnclick=function(){
        oInput.value = "";  // 先将oInput值清空,否则选择图片与上次相同时change事件不会触发
        //清空已选图片
        $('.float').remove();
        dataArr = [];
        index = 0;
        oInput.click();
      }

      oAdd.οnclick=function(){
        oInput.value = "";  // 先将oInput值清空,否则选择图片与上次相同时change事件不会触发
        oInput.click();
      }

      oSubmit.οnclick=function(){
        if(!dataArr.length){
          return alert('请先选择文件');
        }
        send();
      }
    }
    /*
     用ajax发送fd参数时要告诉jQuery不要去处理发送的数据,
     不要去设置Content-Type请求头才可以发送成功,否则会报“Illegal invocation”的错误,
     也就是非法调用,所以要加上“processData: false,contentType: false,”
     * */

    function ReSizePic(ThisPic) {
      var RePicWidth = 200; //这里修改为您想显示的宽度值

      var TrueWidth = ThisPic.width; //图片实际宽度
      var TrueHeight = ThisPic.height; //图片实际高度

      if(TrueWidth>TrueHeight){
        //宽大于高
        var reWidth = RePicWidth;
        ThisPic.width = reWidth;
        //垂直居中
        var nowHeight = TrueHeight * (reWidth/TrueWidth);
        return nowHeight; //将图片修改后的高度返回,供垂直居中用
      }else{
        //宽小于高
        var reHeight = RePicWidth;
        ThisPic.height = reHeight;
      }
    }
  </script>
</head>
<body>
<div class="container">
  <label>请选择一个图像文件:</label>
  <button id="select">(重新)选择图片</button>
  <button id="add">(追加)图片</button>

<form action="" method="post" enctype="multipart/form-data">
  <input type="file" id="file_input" name="image[]" multiple/>
  <!--用input标签并选择type=file,记得带上multiple,不然就只能单选图片了-->
  <button id="submit">提交</button>
</form>

</div>
</body>
</html>

controller

$image=request()->file('image');
print_r($image);

3、over!!!

希望本文所述对大家基于ThinkPHP框架的PHP程序设计有所帮助。

PHP 相关文章推荐
php 数组排序 array_multisort与uasort的区别
Mar 24 PHP
PHP三元运算符的结合性介绍
Jan 10 PHP
让PHP更快的提供文件下载的代码
Jun 13 PHP
一个显示效果非常不错的PHP错误、异常处理类
Mar 21 PHP
php内嵌函数用法实例
Mar 20 PHP
WordPress中获取页面链接和标题的相关PHP函数用法解析
Dec 17 PHP
php实现搜索类封装示例
Mar 31 PHP
PHP实现简单ajax Loading加载功能示例
Dec 28 PHP
PHP给源代码加密的几种方法汇总(推荐)
Feb 06 PHP
PHP面向对象程序设计中的self、static、parent关键字用法分析
Aug 14 PHP
laravel框架语言包拓展实现方法分析
Nov 22 PHP
php生成短网址/短链接原理和用法实例分析
May 29 PHP
thinkphp框架实现路由重定义简化url访问地址的方法分析
Apr 04 #PHP
Thinkphp框架使用list_to_tree 实现无限级分类列出所有节点示例
Apr 04 #PHP
thinkphp框架表单数组实现图片批量上传功能示例
Apr 04 #PHP
yii框架结合charjs统计上一年与当前年数据的方法示例
Apr 04 #PHP
yii框架结合charjs实现统计30天数据的方法
Apr 04 #PHP
yii 框架实现按天,月,年,自定义时间段统计数据的方法分析
Apr 04 #PHP
thinkphp5 框架结合plupload实现图片批量上传功能示例
Apr 04 #PHP
You might like
php配置php-fpm启动参数及配置详解
2013/11/04 PHP
PHP如何实现Unicode和Utf-8编码相互转换
2015/07/29 PHP
php中get_magic_quotes_gpc()函数说明
2017/02/06 PHP
使用PHPMailer发送邮件实例
2017/02/15 PHP
Jquery选择器 $实现原理
2009/12/02 Javascript
Javascript实现滚动图片新闻的实例代码
2013/11/27 Javascript
jquery阻止后续事件只执行第一个事件
2014/07/24 Javascript
利用js实现禁止复制文本信息
2015/06/03 Javascript
jQuery中Find选择器用法示例
2016/09/21 Javascript
javascript实现最长公共子序列实例代码
2018/02/05 Javascript
使用vuex缓存数据并优化自己的vuex-cache
2018/05/30 Javascript
详解vuex commit保存数据技巧
2018/12/25 Javascript
vue+mock.js实现前后端分离
2019/07/24 Javascript
ES10的13个新特性示例(小结)
2019/09/23 Javascript
Angular之jwt令牌身份验证的实现
2020/02/14 Javascript
在NodeJs中使用node-schedule增加定时器任务的方法
2020/06/08 NodeJs
Node.js中的异步生成器与异步迭代详解
2021/01/31 Javascript
[01:13]2014DOTA2西雅图邀请赛 舌尖上的TI4
2014/07/08 DOTA
[03:06]2018年度CS GO最具人气解说-完美盛典
2018/12/16 DOTA
python复制文件代码实现
2013/12/23 Python
Python面向对象基础入门之编码细节与注意事项
2018/12/11 Python
python爬虫基础教程:requests库(二)代码实例
2019/04/09 Python
使用python3调用wxpy模块监控linux日志并定时发送消息给群组或好友
2019/06/05 Python
Python3中urlencode和urldecode的用法详解
2019/07/23 Python
pyinstaller打包程序exe踩过的坑
2019/11/19 Python
python实现在一个画布上画多个子图
2020/01/19 Python
python 解决tqdm模块不能单行显示的问题
2020/02/19 Python
No module named ‘win32gui‘ 的解决方法(踩坑之旅)
2021/02/18 Python
凯特方迪化妆品官网:Kat Von D Beauty
2016/11/15 全球购物
实习教师自我鉴定
2013/12/12 职场文书
党员干部2014全国两会学习心得体会
2014/03/10 职场文书
一份没有按时交货失信于客户的检讨书
2014/09/19 职场文书
2014年物资管理工作总结
2014/12/02 职场文书
党员干部学法用法心得体会
2016/01/21 职场文书
Apache POI的基本使用详解
2021/11/07 Servers
Dashboard管理Kubernetes集群与API访问配置
2022/04/01 Servers