首页 > 技术文章 > html上传多图并预览

ovim 2019-03-23 11:13 原文

当前代码功能有一些缺陷,可以关注最新的博客进行查看(https://www.cnblogs.com/yulongcode/p/12442054.html),如果您有兴趣,可以自己研究研究,欢迎沟通交流

====================================================================================

涉及知识:base64处理图片,ajax,js,thinkphp

效果图:

 

代码实现:

html:

  1 <!DOCTYPE html>
  2 <html>
  3 <head>
  4     <meta charset="UTF-8">
  5     <title>showImages</title>
  6     <style type="text/css">
  7         .float{
  8             float:left;
  9             width : 200px;
 10             height: 200px;
 11             overflow: hidden;
 12             border: 1px solid #CCCCCC;
 13             border-radius: 10px;
 14             padding: 5px;
 15             margin: 5px;
 16         }
 17         img{
 18             position: relative;
 19         }
 20         .result{
 21             width: 200px;
 22             height: 200px;
 23             text-align: center;
 24             box-sizing: border-box;
 25         }
 26         #file_input{
 27             display: none;
 28         }
 29         .delete{
 30             width: 200px;
 31             height:200px;
 32             position: absolute;
 33             text-align: center;
 34             line-height: 200px;
 35             z-index: 10;
 36             font-size: 30px;
 37             background-color: rgba(255,255,255,0.8);
 38             color: #777;
 39             opacity: 0;
 40             transition-duration: :0.7s;
 41             -webkit-transition-duration: 0.7s;
 42         }
 43         .delete:hover{
 44             cursor: pointer;
 45             opacity: 1;
 46         }
 47     </style>
 48     <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
 49     <script type="text/javascript">
 50         window.onload = function(){
 51             var input = document.getElementById("file_input");
 52             var result;
 53             var dataArr = []; // 储存所选图片的结果(文件名和base64数据)
 54             var fd;  //FormData方式发送请求
 55             var oSelect = document.getElementById("select");
 56             var oAdd = document.getElementById("add");
 57             var oSubmit = document.getElementById("submit");
 58             var oInput = document.getElementById("file_input");
 59 
 60             if(typeof FileReader==='undefined'){
 61                 alert("抱歉,你的浏览器不支持 FileReader");
 62                 input.setAttribute('disabled','disabled');
 63             }else{
 64                 input.addEventListener('change',readFile,false);
 65             }     //handler
 66 
 67             function readFile(){
 68                 fd = new FormData();
 69                 var iLen = this.files.length;
 70                 var index = 0;
 71                 for(var i=0;i<iLen;i++){
 72                     if (!input['value'].match(/.jpg|.gif|.png|.jpeg|.bmp/i)){  //判断上传文件格式
 73                         return alert("上传的图片格式不正确,请重新选择");
 74                     }
 75                     var reader = new FileReader();
 76                     reader.index = i;
 77                     fd.append(i,this.files[i]);
 78                     reader.readAsDataURL(this.files[i]);  //转成base64
 79                     reader.fileName = this.files[i].name;
 80 
 81                     reader.onload = function(e){
 82                         var imgMsg = {
 83                             name : this.fileName,//获取文件名
 84                             base64 : this.result   //reader.readAsDataURL方法执行完后,base64数据储存在reader.result里
 85                         }
 86                         dataArr.push(imgMsg);
 87                         result = '<div class="delete">delete</div><div class="result"><img src="'+this.result+'" alt=""/></div>';
 88                         var div = document.createElement('div');
 89                         div.innerHTML = result;
 90                         div['className'] = 'float';
 91                         div['index'] = index;
 92                         document.getElementsByTagName('body')[0].appendChild(div);    //插入dom树
 93                         var img = div.getElementsByTagName('img')[0];
 94                         img.onload = function(){
 95                             var nowHeight = ReSizePic(this); //设置图片大小
 96                             this.parentNode.style.display = 'block';
 97                             var oParent = this.parentNode;
 98                             if(nowHeight){
 99                                 oParent.style.paddingTop = (oParent.offsetHeight - nowHeight)/2 + 'px';
100                             }
101                         }
102 
103                         div.onclick = function(){
104                             this.remove();                  // 在页面中删除该图片元素
105                             delete dataArr[this.index];  // 删除dataArr对应的数据
106 
107                         }
108                         index++;
109                     }
110                 }
111             }
112 
113 
114             function send(){
115                 var submitArr = [];
116                 for (var i = 0; i < dataArr.length; i++) {
117                     if (dataArr[i]) {
118                         submitArr.push(dataArr[i]);
119                     }
120                 }
121                 // console.log('提交的数据:'+JSON.stringify(submitArr))
122                 $.ajax({
123                     type : "post",
124                     url : "{:URL('index/Index/index')}",
125                     data : {
126                         img : JSON.stringify(submitArr)
127                     },
128                     // processData: false,   //用FormData传fd时需有这两项
129                     // contentType: false,
130                     success : function(data){
131                         // console.log('返回的数据:'+data);
132                         if(data ==1)
133                         {
134                             alert('yes');
135                         }else {
136                             alert('no');
137                         }
138                     }
139                 })
140             }
141 
142             oSelect.onclick=function(){
143                 oInput.value = "";   // 先将oInput值清空,否则选择图片与上次相同时change事件不会触发
144                 //清空已选图片
145                 $('.float').remove();
146                 dataArr = [];
147                 index = 0;
148                 oInput.click();
149             }
150 
151             oAdd.onclick=function(){
152                 oInput.value = "";   // 先将oInput值清空,否则选择图片与上次相同时change事件不会触发
153                 oInput.click();
154             }
155 
156 
157             oSubmit.onclick=function(){
158                 if(!dataArr.length){
159                     return alert('请先选择文件');
160                 }
161                 send();
162             }
163         }
164         /*
165          用ajax发送fd参数时要告诉jQuery不要去处理发送的数据,
166          不要去设置Content-Type请求头才可以发送成功,否则会报“Illegal invocation”的错误,
167          也就是非法调用,所以要加上“processData: false,contentType: false,”
168          * */
169 
170         function ReSizePic(ThisPic) {
171             var RePicWidth = 200; //这里修改为您想显示的宽度值
172 
173             var TrueWidth = ThisPic.width; //图片实际宽度
174             var TrueHeight = ThisPic.height; //图片实际高度
175 
176             if(TrueWidth>TrueHeight){
177                 //宽大于高
178                 var reWidth = RePicWidth;
179                 ThisPic.width = reWidth;
180                 //垂直居中
181                 var nowHeight = TrueHeight * (reWidth/TrueWidth);
182                 return nowHeight;  //将图片修改后的高度返回,供垂直居中用
183             }else{
184                 //宽小于高
185                 var reHeight = RePicWidth;
186                 ThisPic.height = reHeight;
187             }
188         }
189     </script>
190 </head>
191 <body>
192 <div class="container">
193     <label>请选择一个图像文件:</label>
194     <button id="select">(重新)选择图片</button>
195     <button id="add">(追加)图片</button>
196 
197     <form action="" >
198         <input type="file" id="file_input" name="image[]" multiple/>
199         <!--用input标签并选择type=file,记得带上multiple,不然就只能单选图片了-->
200         <button id="submit">提交</button>
201     </form>
202 
203 </div>
204 </body>
205 </html>

 

 php:

<?php
namespace app\index\controller;

use think\Controller;
use think\Db;

class Index extends Controller
{
    public function index()
    {
        if(request()->isAjax())
        {
            $img = request()->post('img');  //接收图片信息
            $arr = json_decode($img,true); //转成数组
            $ImgUrl = [];
            for($i=0;$i<count($arr);$i++)
            {
                $houzhui = substr(strrchr($arr[$i]['name'], '.'), 1);//获取文件后缀名
                $image = $arr[$i]['base64'];
                //这里的图片名称就是你存入数据库时的图片名称
                $imageName = date("His",time())."_".rand(1111,9999).'.'.$houzhui;  
                   // 判断是否有逗号 如果有就截取后半部分
                if (strstr($image,",")){
                    $image = explode(',',$image);
                    $image = $image[1];
                }
                //图片保存路径,可根据使用框架目录的不同自定义目录
                $path = ROOT_PATH . 'public' . DS .'static'. DS .date("Ymd",time());
                // 判断目录是否存在 不存在就创建 并赋予777权限
                if (!is_dir($path)){ //判断目录是否存在 不存在就创建
                    mkdir($path,0777,true);
                }
                $imageSrc=  $path."/". $imageName;
                // 生成图片 返回的是字节数
                $r = file_put_contents($imageSrc, base64_decode($image));
                if (!$r) {
                    $ImgUrl[$i] = "===图片生成失败===";
                }else{
                    $ImgUrl[$i] = $imageName;
                }
            }
            //$ImgUrl 即为上传之后的图片名称,是逗号隔开的字符串
            $ImgUrl = implode(',',$ImgUrl);
            //将字符串存入数据库
            $data = Db::table('testimg')->insert(['val'=>$ImgUrl]);
            if($data)
            {
                return 1;
            }else{
                return 0;
            }
        }else{
            return view();
        }
    }
}

 

 over!over!over!

推荐阅读