微信公众号aiax上传多张图片限制两张

微信公众号aiax上传多张图片限制两张

      https://gitee.com/yinfanliang/chengyang.git 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>demo页面</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <link rel="stylesheet" href="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.bootcss.com/layer/3.1.0/mobile/need/layer.css">
    <link rel="stylesheet" href="./css/style.css">
    <script src="http://cdn.static.runoob.com/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script src="https://cdn.bootcss.com/layer/3.1.0/mobile/layer.js"></script>
    <script src="./js/lrz.bundle.js"></script>
</head>
<body style="background-color: #dcdede">
<div class="container-fluid">
    <form role="form">
        
        <div class="form-group">
            <label for="name">举报描述:</label>
            <textarea class="form-control" id="content" name="content" rows="8"
                      placeholder="请输入举报内容"></textarea>
        </div>
        <!--上传图片开始-->

        <label for="name">拍照:</label>
        <!--    照片添加    -->
        <div class="z_photo">
            <div class="z_file">
                <input type="file" name="file" id="file" value="" accept="image/*" multiple
                       onchange="imgChange('z_photo','z_file');"/>
            </div>

        </div>

        <!--遮罩层-->
        <div class="z_mask">
            <!--弹出框-->
            <div class="z_alert">
                <p>确定要删除这张图片吗?</p>
                <p>
                    <span class="z_cancel">取消</span>
                    <span class="z_sure">确定</span>
                </p>
            </div>
        </div>
     
<script type="text/javascript">
    var file = document.getElementById('file');
    var u = navigator.userAgent, app = navigator.appVersion;
    var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; //android终端或者uc浏览器
    var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
    // alert('是否是Android:'+isAndroid);
    // alert('是否是iOS:'+isiOS);
    (function (doc, win) {
        var docEl = doc.documentElement,
            resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
            recalc = function () {
                var clientWidth = docEl.clientWidth;
                if (!clientWidth) return;
                if (clientWidth >= 640) {
                    docEl.style.fontSize = '100px';
                } else {
                    docEl.style.fontSize = 100 * (clientWidth / 640) + 'px';
                }
            };

        if (!doc.addEventListener) return;
        win.addEventListener(resizeEvt, recalc, false);
        doc.addEventListener('DOMContentLoaded', recalc, false);
    })(document, window);
    var num = 0;
    if (isAndroid) {
        var formdata = new FormData();
        file.addEventListener('change', imgChangeUpload, false);

        function imgChangeUpload() {
            formdata.append("file", $('#file')[0].files[0]);

            if (num >= 2) {
                layer.open({
                    content: '最多上传2张'
                    , skin: 'msg'
                    , time: 2 //2秒后自动关闭
                });
                num -= 1;
                return false;
            }
            $.ajax({
                url: 'http://' + "<?php echo $_SERVER['HTTP_HOST']?>" + '/weixin/dataHandel.php?river_id=4&fun=saveUploadImg&isAndroid=1',
                type: 'POST',
                cache: false,
                data: formdata,
                timeout: 5000,
                //必须false才会避开jQuery对 formdata 的默认处理
                // XMLHttpRequest会对 formdata 进行正确的处理
                processData: false,
                //必须false才会自动加上正确的Content-Type
                contentType: false,
                xhrFields: {
                    withCredentials: true
                },
                success: function (data) {
                    data = JSON.parse(data);
                    var pic = $("#pic").val();
                    if (pic.length == 0) {
                        $('#pic').val(data.path)
                    } else {
                        $('#pic').val(pic + ',' + data.path)
                    }
                    if (data.code > 0) {
                        num = num+1;
                        layer.open({
                            content: '上传成功'
                            , skin: 'msg'
                            , time: 2 //2秒后自动关闭
                        });
                        var img = document.createElement("img");
                        img.setAttribute("src", data.path);
                        var imgAdd = document.createElement("div");
                        imgAdd.setAttribute("class", "z_addImg");
                        imgAdd.appendChild(img);
                        var imgContainer = document.getElementsByClassName('z_photo')[0];
                        imgContainer.appendChild(imgAdd);
                        return false;
                    } else {
                        layer.open({
                            content: '上传失败'
                            , skin: 'msg'
                            , time: 2 //2秒后自动关闭
                        });
                        return false;
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {

                }
                // var xml=
            });
        }
    } else {
        //onchange="imgChange('z_photo','z_file');"
        file.addEventListener('change', imgChange, false);

        function imgChange() {
            //获取点击的文本框
            var file = document.getElementById("file");
            var obj1 = 'z_photo', obj2 = 'z_file';
            /* 压缩图片 */

            //存放图片的父级元素
            var imgContainer = document.getElementsByClassName(obj1)[0];
            //获取的图片文件
            var fileList = file.files;

            //文本框的父级元素
            var input = document.getElementsByClassName(obj2)[0];
            var imgArr = [];
            //遍历获取到得图片文件
            num += fileList.length;
            if (num > 2 || fileList.length > 2) {
                layer.open({
                    content: '最多上传2张'
                    , skin: 'msg'
                    , time: 2 //2秒后自动关闭
                });
                num -= 1;
                return false;
            }
            for (var i = 0; i < fileList.length; i++) {
                lrz(file.files[i], {
                    width: 300 //设置压缩参数
                }).then(function (rst) {
                    /* 处理成功后执行 */
                    // console.log(rst.base64);
                    rst.formData.append('base64img', rst.base64); // 添加额外参数

                    $.ajax({
                        url: 'http://' + "<?php echo $_SERVER['HTTP_HOST']?>" + '/weixin/dataHandel.php?river_id=4&fun=saveUploadImg',
                        type: "POST",
                        data: rst.formData,
                        dataType: 'json',
                        processData: false,
                        contentType: false,
                        success: function (data) {
                            var pic = $("#pic").val();
                            if (pic.length == 0) {
                                $('#pic').val(data.path)
                            } else {
                                $('#pic').val(pic + ',' + data.path)
                            }
                            if (data.code > 0) {
                                layer.open({
                                    content: '上传成功'
                                    , skin: 'msg'
                                    , time: 2 //2秒后自动关闭
                                });
                                return false;
                            } else {
                                layer.open({
                                    content: '上传失败'
                                    , skin: 'msg'
                                    , time: 2 //2秒后自动关闭
                                });
                                return false;
                            }
                        }
                    });
                }).catch(function (err) {
                    layer.open({
                        content: ' 处理失败'
                        , skin: 'msg'
                        , time: 2 //2秒后自动关闭
                    });
                    /* 处理失败后执行 */
                }).always(function () {
                    /* 必然执行 */
                });
                var imgUrl = window.URL.createObjectURL(file.files[i]);
                imgArr.push(imgUrl);
                var img = document.createElement("img");
                img.setAttribute("src", imgArr[i]);
                var imgAdd = document.createElement("div");
                imgAdd.setAttribute("class", "z_addImg");
                imgAdd.appendChild(img);
                imgContainer.appendChild(imgAdd);
            }
            ;
            imgRemove();
        }; //结束
    }


    function imgRemove() {

        var imgList = document.getElementsByClassName("z_addImg");
        var mask = document.getElementsByClassName("z_mask")[0];
        var cancel = document.getElementsByClassName("z_cancel")[0];
        var sure = document.getElementsByClassName("z_sure")[0];
        for (var j = 0; j < imgList.length; j++) {
            imgList[j].index = j;
            imgList[j].onclick = function () {
                var t = this;
                mask.style.display = "block";
                cancel.onclick = function () {
                    mask.style.display = "none";
                };
                sure.onclick = function () {
                    num = num - 1;
                    mask.style.display = "none";
                    t.style.display = "none";
                };

            }
        }
        ;
    };

</script>
<!--上传图片结束--> <?php if (isset($_GET['id'])) { ?> <input type="hidden" value="<?php echo $_GET['id'] ?>" name="open_id" id="open_id"> <?php } ?> <input type="hidden" value="" name="pic" id="pic"> <button type="button" class="btn btn-primary btn-lg btn-block btn-add" id="sub" style="margin-top: 50px;">提交 </button> </form></div><script> var is_submit = false; //限制提交频率 $(document).ready(function () { $(document).on('click', '.btn-add', function () { var content = $("#content").val(), open_id = $('#open_id').val(), river_id = $('#river_id').val(),pic=$('#pic').val(); var url = 'http://' + "'; var dataPost = {content: content, open_id: open_id, river_id: river_id,pic:pic}; if (content.length <= 0) { layer.open({ content: '请填写举报内容' , skin: 'msg' , time: 2 //2秒后自动关闭 }); return false; } if (is_submit) { layer.open({ content: '5分钟内只能提交一次' , skin: 'msg' , time: 2 //2秒后自动关闭 }); return false; } $.ajax({ url: url, dataType: 'json', type: 'post', data: dataPost, cache: false, async: true, beforeSend: function (XMLHttpRequest) { $('#sub').removeClass('btn-add'); }, complete: function (XMLHttpRequest) { // layer.open({ // type: 2 // ,content: '提交中...', // shadeClose:false // }) // layer.closeAll(); //疯狂模式,关闭所有层 $('#sub').addClass('btn-add'); }, success: function (json) { if (json.status > 0) { var url = 'http://' + "<?php echo $_SERVER['HTTP_HOST']?>" + '/'; window.location.href = url; is_submit = true; } else { layer.open({ content: json.msg , skin: 'msg' , time: 2 //2秒后自动关闭 }); } }, error: function () { layer.open({ content: '请求失败,请稍后重试....' , skin: 'msg' , time: 2 //2秒后自动关闭 }); } }); // 模拟1s的加载过程 setTimeout(function () { // 重置加载flag is_submit = false; }, 50000); }); });</script></body></html>
 
 public static function saveUploadImg()
    {
        if(isset($_GET['isAndroid'])){
            $output_directory = './upload'; //设置图片存放路径
            /* 检查并创建图片存放目录 */
            if (!file_exists($output_directory)) {
                mkdir($output_directory, 0777);
            }
            $upload=new UploadFile();
            $upload->maxSize  = 3*pow(2,20) ;// 设置附件上传大小  3M    默认为2M
            $upload->allowExts  = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型   默认为空不检测扩展
            $upload->savePath =  $output_directory;// 设置附件上传目录   默认上传目录为 ./uploads/

            if(!$upload->upload()) {
                // 上传错误提示错误信息
                echo json_encode(['code' => -1,'msg'=>$upload->getErrorMsg()]);
            }else{
                // 上传成功 获取上传文件信息
                $info =  $upload->getUploadFileInfo();
                echo json_encode(['path' => '/weixin/upload/' . $info[0]['savename'], 'code' => 1]);
            }
        }else{
        if (!isset($_POST['base64img'])) return false;
        $base64_image_content = $_POST['base64img'];
        $output_directory = './upload'; //设置图片存放路径

        /* 检查并创建图片存放目录 */
        if (!file_exists($output_directory)) {
            mkdir($output_directory, 0777);
        }
        /* 根据base64编码获取图片类型 */
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)) {
            $image_type = $result[2]; //data:image/jpeg;base64,
            $output_file = $output_directory . '/' . md5(time()) . '.' . $image_type;
        }
        /* 将base64编码转换为图片编码写入文件 */
        $image_binary = base64_decode(str_replace($result[1], '', $base64_image_content));
        if (file_put_contents($output_file, $image_binary)) {
//            echo $output_file; //写入成功输出图片路径
            echo json_encode(['path' => '/weixin' . trim($output_file, '.'), 'code' => 1]);
        } else {
            echo json_encode(['code' => -1]);
        }
        }


    }