关于以base64编码形式上传图片

2018/03/23 12:19
阅读数 3

第一次用,记录一下

 

 

HTML中的样式

HTML代码

  

 1             <li class="orther" style="padding-top: 15px;">
 2                             <p>商品封面</p>
 3                             <div class="img-area">
 4                                 <div class="img-cont">
 5                                     <input type="file" id='id-pic' name='pic' accept="image/*" />
 6                                     <div id='pic-empty-result'>
 7                                         <img src="__PUBLIC__/home/images/file_bg.png" />
 8                                     </div>
 9                                     <img style='width: 100%' id='pic-result'/>
10                                 </div>
11                             </div>
12                         </li>
13                         <li class="orther" style="padding-bottom: 15px;">
14                             <p>商品轮播</p>
15                             <div class="img-area">
16                                 <div class="img-cont">
17                                     <input type="file" id='id-pic1' name='pic1' accept="image/*" />
18                                     <div id='pic1-empty-result'>
19                                         <img src="__PUBLIC__/home/images/file_bg.png" />
20                                     </div>
21                                     <img style='width: 100%' id='pic1-result'/>
22                                 </div>
23                                 <div class="img-cont">
24                                     <input type="file" id='id-pic2' name='pic2' accept="image/*" />
25                                     <div id='pic2-empty-result'>
26                                         <img src="__PUBLIC__/home/images/file_bg.png" />
27                                     </div>
28                                     <img style='width: 100%' id='pic2-result'/>
29                                 </div>
30                                 <div class="img-cont">
31                                     <input type="file" id='id-pic3' name='pic3' accept="image/*" />
32                                     <div id='pic3-empty-result'>
33                                         <img src="__PUBLIC__/home/images/file_bg.png" />
34                                     </div>
35                                     <img style='width: 100%' id='pic3-result'/>
36                                 </div>
37                                 <div class="img-cont">
38                                     <input type="file" id='id-pic4' name='pic4' accept="image/*" />
39                                     <div id='pic4-empty-result'>
40                                         <img src="__PUBLIC__/home/images/file_bg.png" />
41                                     </div>
42                                     <img style='width: 100%' id='pic4-result'/>
43                                 </div>
44                                 <div class="img-cont">
45                                     <input type="file" id='id-pic5' name='pic5' accept="image/*" />
46                                     <div id='pic5-empty-result'>
47                                         <img src="__PUBLIC__/home/images/file_bg.png" />
48                                     </div>
49                                     <img style='width: 100%' id='pic5-result'/>
50                                 </div>
51                             </div>
52                         </li>

 

对应的Js 处理代码

<script>
    window.onload=function(){
        document.getElementById("id-pic").addEventListener("change", function(){
            onFileChange(this,"pic-result","pic-empty-result")
        });
        document.getElementById("id-pic1").addEventListener("change", function(){
            onFileChange(this,"pic1-result","pic1-empty-result")
        });
        document.getElementById("id-pic2").addEventListener("change", function(){
            onFileChange(this,"pic2-result","pic2-empty-result")
        });
        document.getElementById("id-pic3").addEventListener("change", function(){
            onFileChange(this,"pic3-result","pic3-empty-result")
        });
        document.getElementById("id-pic4").addEventListener("change", function(){
            onFileChange(this,"pic4-result","pic4-empty-result")
        });
        document.getElementById("id-pic5").addEventListener("change", function(){
            onFileChange(this,"pic5-result","pic5-empty-result")
        });
        // document.getElementsByClassName("pub-btn")[0].addEventListener("click", function(){
        //     submit();
        // });
    };
    /**
     * 选中图片时的处理
     * @param {*} fileObj input file元素
     * @param {*} el //选中后用于显示图片的元素ID
     * @param {*} btnel //未选中图片时显示的按钮区域ID
     */
    function onFileChange(fileObj,el,btnel){
        var windowURL = window.URL || window.webkitURL;
        var dataURL;
        var imgObj = document.getElementById(el);
        document.getElementById(btnel).style.display="none";
        imgObj.style.display="block";
        if (fileObj && fileObj.files && fileObj.files[0]) {
            dataURL = windowURL.createObjectURL(fileObj.files[0]);
            imgObj.src=dataURL;
        } else {
            dataURL = fileObj.value;
            imgObj.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
            imgObj.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = dataURL;
        }
    }
    /**
     * 将图片压缩后返回base64格式的数据
     * @param {*} image img元素
     * @param {*} width 压缩后图片宽度
     * @param {*} height 压缩后图片高度
     * @param {*} qua //图片质量1-100
     */
    function compressImageTobase64(image,width,height,qua){
        var quality = qua ? qua / 100 : 0.8;
        var canvas = document.createElement("canvas"),
            ctx = canvas.getContext('2d');

        var w = image.naturalWidth,
            h = image.naturalHeight;
        if(w<=1 || h<=1){
            return false;
        }
        canvas.width = width||w;
        canvas.height = height||h;
        ctx.drawImage(image, 0, 0, w, h, 0, 0, width||w, height||h);
        var data = canvas.toDataURL("image/jpeg", quality);
        return data;
    }
    //提交
    function submit(){
        //1、form提交
        //document.getElementById("pubForm").submit();
        //2、压缩后ajax提交
        var pic_data=compressImageTobase64(document.getElementById("pic-result"),200,100,90);
        var pic1_data=compressImageTobase64(document.getElementById("pic1-result"),200,100,90);
        var pic2_data=compressImageTobase64(document.getElementById("pic2-result"),200,100,90);
        var pic3_data=compressImageTobase64(document.getElementById("pic3-result"),200,100,90);
        var pic4_data=compressImageTobase64(document.getElementById("pic4-result"),200,100,90);
        var pic5_data=compressImageTobase64(document.getElementById("pic5-result"),200,100,90);
        var formData = new FormData();
        if(pic_data==false){
            layer.alert("请上传产品封面!");
            return false;
        }else{
            formData.append("pic",pic_data);
        }
        if(pic1_data==false && pic2_data==false && pic3_data==false && pic4_data==false && pic5_data==false){
            layer.alert("请至少选择一张轮播图!");
            return false;
        }else{
            if(pic1_data!=false) formData.append("pic1",pic1_data);
            if(pic2_data!=false) formData.append("pic2",pic2_data);
            if(pic3_data!=false) formData.append("pic3",pic3_data);
            if(pic4_data!=false) formData.append("pic4",pic4_data);
            if(pic5_data!=false) formData.append("pic5",pic5_data);
        }
        // 需引入jQuery
        $.ajax({
            url:"{<:U('Home/Product/upload')>}",
            type: 'POST',
            cache: false,
            data: formData,
            timeout:180000,
            processData: false,
            contentType: false,
            success:function(r){
               return r;
            },
            error:function(r){
            }
        });
    }
</script>

 

PHP端的处理

public function upload(){
        $pics =array_values(I('post.'));
        $dir = "./Uploads/Product/";
        //判断目录是否存在  不存在就创建
        if(!file_exists($dir)){
            mkdir($dir,0777);
        }
        $thumb = "";
        $lunbo = [];
        $error = [];
        foreach($pics as $key=>$vo){
            if(preg_match('/^(data:\s*image\/(\w+);base64,)/', $vo, $result)){
                $type = $result[2];
                if(in_array($type,array('jpeg','jpg','gif','bmp','png'))){
                    $file_name= uniqid().'.'.$type;
                    $new_file = $dir.$file_name;
                    $xx = base64_decode(str_replace($result[1], '', $vo));
                    if(file_put_contents($new_file,$xx)){
                        if($key==0){
                            $thumb = $file_name;
                        }else{
                            $lunbo[]=$file_name;
                        }
                    }else{
                        $error[] = "$key 图片上传失败";
                    }
                }else{
                    //文件类型错误
                    $error[] =  "$key 图片上传类型错误";
                }
            }
        }
        if($thumb!=""&&count($lunbo)>=1){
            session("thumb",$thumb);
            session("lunbo",$lunbo);
            echo true;
        }else{
            echo false;
        }
    }

 

 

总结:

  主要还是JS页面的处理,将图片转换成base64字符串。通过ajax将字符串传递到后端

  后端则使用正则形式,将格式化字符串所表达的内容取出,

  再针对图片字符串进行file_put_contents();

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部