写了个Ajax无刷新上传上传图片的小插件

17-04-07 00:30 字数 3658 阅读 3986 已编辑

原理: 隐藏iframe提交数据到后台(php)

js源码

/**
 * (伪)无刷新上传图片
 * @requires jquery,bootstrap(.css),font-awesome
 * @author saonian
 * @date 2017年4月6日
 * @time 22:54:43
 */
$(function () {
    var ico_left = (lu_upload_div_w - 15) / 2;
    var ico_top = (lu_upload_div_h - 14) /2;
    var html =
        '<form action="'+lu_upload_url+'" id="title_pic_form" method="post" role="form" enctype="multipart/form-data">'
        +'<div class="form-group">'
        +'<div class="pre_article_pic text-center" style="width: '+lu_upload_div_w+'px; height: '+lu_upload_div_h+'px;position: relative;background-color:#f3f3f3;">'
        +'<span class="pic_noticle" style="position: absolute;display: block;margin-top:'+ico_top+'px;margin-left: '+ico_left+'px;webkit-transition: all .05s ease-in-out; -moz-transition: all .05s ease-in-out; -o-transition: all .05s ease-in-out;transition: all .05s ease-in-out;"><i class="fa fa-camera"></i></span>'
        +'<input type="file" name="title_pic_m" class="title_pic_m" id="title_pic_m" style="width: '+lu_upload_div_w+'px; height: '+lu_upload_div_h+'px;opacity: 0;cursor: pointer;position: absolute;" title="点击上传题图">'
        +'<div class="loading text-center" style="display: none;position: absolute;margin-top:'+ico_top+'px;margin-left: '+ico_left+'px;"><i class="fa fa-spinner fa-spin"></i></div>'
        +'<img src="" alt="img_error" class="img-rounded pre_pic_re" style="display:none;width: '+lu_upload_div_w+'px; height: '+lu_upload_div_h+'px;">'
        +'<div class="edit_img btn-group-xs" style="display: none;position: absolute;right: 0;bottom: 0;opacity: .9;" role="group">'
        +'<button type="button" class="reload_img btn-xs btn-info"><i class="fa fa-refresh"></i></button>'
        +'<button type="button" class="del_img btn-xs btn-danger"><i class="fa fa-trash"></i></button>'
        +'</div>'
        +'</div>'
        +'</div>'
        +'</form>';
   $('body').find('#lu_upload_div').append(html);
   $('body').find('#'+_custom_form+'').append('<input type="hidden" name="article_pic" value=""> <input type="hidden" name="article_pic_m" value="">');
   var _title_pic = $(".title_pic_m");
   if(_title_pic && _title_pic.length >0){
       $(document).on('mouseover mouseout','.title_pic_m',function (e) {
           if(e.type === 'mouseover'){
               _title_pic.tooltip('show');return false;
           }else if (e.type === 'mouseout'){
               _title_pic.tooltip('hide');return false;
           }
       })
   }
    //创建一个隐藏的iframe,用于上传图片及接收php返回的图片地址
    var ifm_id = Math.floor(Math.random() * 1000);
    $(document).on('change','#title_pic_m',function () {
        var upload_file = $(this).val();
        if(upload_file != ''){
            var ifm_name = 'title_pic_form' + ifm_id;
            var ifm_doc = '<iframe width="0" height="0" frameborder="0" name="'+ifm_name+'" id="my_ifm"></iframe>';
            $("body").append(ifm_doc);
            $("#title_pic_form").attr('target', ifm_name).submit();
            $(".loading").show();
            $(".pic_noticle").hide();
            $("#my_ifm").load(function () {
                var responseText = $('iframe')[0].contentDocument.body.textContent;
                var responseData = JSON.parse(responseText) || {};
                if(responseData.ok == 1){
                    $(".loading").hide();
                    $("#title_pic_m").hide();
                    $(".edit_img").show();
                    $('input[name="article_pic"]').val(responseData.data);
                    $('input[name="article_pic_m"]').val(responseData.data_m);
                    $(".pre_article_pic").show().children('img').attr('src',''+responseData.data+'').show();
                }else{
                    alert(responseData.info);
                    $(".loading").hide();
                    $(".pic_noticle").show();
                }
            });
        }
    });

    //重新上传题图
    $(document).on('click','.reload_img',function () {
        $("#title_pic_m").show().trigger("click");
        var title_pic = $('input[name="article_pic"]').val();
        var title_pic_m = $('input[name="article_pic_m"]').val();
        var _this = $(this);
        $.ajax({
            url:lu_upload_del_url,
            type:"post",
            data:{title_pic:title_pic,title_pic_m:title_pic_m},
            dataType:'json',
            beforeSend : function () {
                _this.unbind('click');
            },
            success: function (response) {
                _this.bind('click');
                $(".edit_img").hide();
                if(response.ok == 1){
                    $(".pre_pic_re").attr('src','').hide();
                    $('input[name="article_pic"]').val('');
                    $('input[name="article_pic_m"]').val('');
                }else{
                    alert(response.info);
                }

            }
        });
    });

    //删除题图
    $(document).on('click','.del_img',function () {
        if (confirm('确定删除题图吗?')){
            var _this = $(this);
            var title_pic = $('input[name="article_pic"]').val();
            var title_pic_m = $('input[name="article_pic_m"]').val();
            $.ajax({
                url:lu_upload_del_url,
                type:"post",
                data:{title_pic:title_pic,title_pic_m:title_pic_m},
                dataType:'json',
                beforeSend : function () {
                    _this.unbind('click');
                },
                success: function (response) {
                    _this.bind('click');
                    $(".edit_img").hide();
                    $("#title_pic_m").show();
                    $(".pic_noticle").show();
                    if(response.ok == 1){
                        $(".pre_pic_re").attr('src','').hide();
                        $('input[name="article_pic"]').val('');
                        $('input[name="article_pic_m"]').val('');
                    }else{
                        alert(response.info);
                    }

                }
            });
        }
    });
});

使用方法

<script src="__PUBLIC__/js/luz_upload.js" type="text/javascript"></script>
<script>
    var lu_upload_url = '/up_title_pic_m';//图片上传地址
    var lu_upload_del_url = '/del_article_pic';//图片删除地址
    var lu_upload_div_w = '120';//预览图宽度
    var lu_upload_div_h = '80';//预览图高度
    var _custom_form = 'c_form';//表单ID
</script>

后台处理

后台(以php为例)需要返回以下json字符串

参数 说明
ok 1(成功)0(失败)
info ok0(上传失败)时的错误提示信息
data 图片地址
data_m 手机端图片地址(可选)

上传成功后会在form插入两个隐藏域

<input type="hidden" name="article_pic" value="">
<input type="hidden" name="article_pic_m" value="">

value值为后台传回的图片地址

删除图片

删除图片时会向后台传递两个参数

  • title_pic 图片地址
  • title_pic_m 手机端图片地址

例子

public function del_article_pic(){
        $res = ['ok'=>0,'info'=>''];
        if (checkLogin()){
            if (IS_POST){
                $post_data = I('post.');
                $title_pic = $post_data['title_pic'] ?? '';
                $title_pic_m = $post_data['title_pic_m'] ?? '';
                if (!empty($title_pic) && !empty($title_pic_m)){
                    $title_pic_pathinfo = parse_url($title_pic);
                    $title_pic_m_pathinfo = parse_url($title_pic_m);
                    $title_pic_pathinfo = $title_pic_pathinfo['path'] ?? '';
                    $title_pic_m_pathinfo = $title_pic_m_pathinfo['path'] ?? '';
                    @unlink('.'.$title_pic_pathinfo);
                    @unlink('.'.$title_pic_m_pathinfo);
                    $res['ok'] = 1;
                }
            }
        }

        $this->ajaxReturn($res);
    }
0人点赞>
关注 收藏 改进 举报
1 条评论
排序方式 时间 投票
Up骚年

在【新建主题】中体验此功能!

请登录后发表评论
站长 @ 十七度
文章
384
粉丝
23
喜欢
195
收藏
31
排名 : 1
访问 : 147.83万
私信