【LayerUI】上传图片(多图,非拖拽)

原理:用upload.render() 组件实现上传,服务端保存好图片返回路径,这种只适合上传即保存的功能,如果想上传多张后再一次保存,不建议使用。

<script>
                //多图上传
                layui.use('upload', function () {
                    var $ = layui.jquery
                    , upload = layui.upload;
                    var uploadInstss = upload.render({
                        elem: "#uploadPic"
                        , multiple: true
                        , url: '接口地址'
                        , exts: 'jpg|png' //只允许图片
                        , done: function (res) {
                            $("#noMsgDIV").hide();
                            //如果上传失败
                            if (res.code > 0)
                            {
                                return layer.msg('上传失败');
                            }
                            //上传成功
                            if (!res.error) {
                                AppendPic(res.FileName)
                            }
                        }
                        , error: function () {
                            //演示失败状态,并实现重传
                            var demoText = $('#demoText');
                            demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                            demoText.find('.demo-reload').on('click', function () {
                                uploadInst.upload();
                            });
                        }
                    });
                })

            function AppendPic(FileName) {
                    if ($(".contentpic").length >= 5) {
                        return layer.msg('最多上传5张图片。');
                    }
                    var html = "<div class=\"contentpic\" style=\"display: inline-block;margin:7px;\">" +
                                "<img src=\"" + FileName + "\" style=\"width:240px;height:120px;\" />" +
                                "<div onclick=\"delPic(this)\" class=\"layui-btn layui-btn-sm layui-btn-normal delbtn\"><i class=\"layui-icon\"></i>删 除</div>" +
                                "</div>";

                    var abhtml = $("#Big_ContentPic").html();

                    abhtml += html;
                    $("#Big_ContentPic").html(abhtml)
                }

                function delPic(thisObj) {
                    $(thisObj).parent().remove();
            //这里可写成删除图片ajax请求 }
</script>

猜你喜欢

转载自www.cnblogs.com/laokchen/p/12724397.html