阅读 142

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

这篇文章主要介绍了TP5框架实现一次选择多张图片并预览的方法,结合实例形式详细分析了thinkPHP5基于ajax数据提交上传多张图片与本地预览相关操作技巧,需要的朋友可以参考下

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

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

1、效果图

2、code

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

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

view

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
<!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 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

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

3、over!!!



文章分类
后端
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐