zoukankan      html  css  js  c++  java
  • layui+django 多组图片上传、预览、删除、打标签

    上传多组图片且每组每个图片都要有个标签,标签是动态的

    思路是标签使用逗号分隔的

    先在后台将标签存入列表

    然后前端layui回调时再将下一个标签传入前端

    存储时使用data将标签作为额外参数传入后台

    前端

    引入依赖包

    <link rel="stylesheet" href="/static/layui/css/layui.css">
    <script src="/static/layui/layui.js"></script>
    <script src="/static/js/jquery-1.8.2.min.js"></script>
     
    前端代码
    {% csrf_token %}
    <div id="provena">{{text}}</div>
    <div>
        <button type="button" class="layui-btn layui-btn-lg" id="test1">
            <i class="layui-icon">&#xe67c;</i>选择图片
          </button>
          <div class="layui-row" style="1500px;">
            <div class="layui-upload-list"></div>
        </div>
            <input type="text" name="provename" id="provename" value={{text}} hidden=True  readonly="readonly"> 
            <input type="submit"  id ="abc" class="layui-btn layui-btn-radius layui-btn-normal" style="font-size: 25px;" value=上传图片>

    </div>
    <script>
        layui.use(['upload', 'jquery'], function(){
          var upload = layui.upload;
              var $ = layui.jquery;
              //执行实例
              var uploadInst = upload.render({
                  elem: '#test1', //绑定元素
                  multiple: true,  //多图上传
                  method: 'POST',
                  auto: false,  //关闭自动上传
                  data: {
                        'csrfmiddlewaretoken': function () {    //post传输需要csrf验证
                            return $(':input:first').val()
                        },
                        provename: function(){
                            return $('#provename').val();  //传入后台额为动态参数
                        }
                    },
                  acceptMime: 'image/*',
                  bindAction: "#abc",//绑定上传
                  url: "{% url 'provee' %}", //上传接口
                  choose: function (obj) { //obj参数包含的信息,跟 choose回调完全一致
                      //将每次选择的文件追加到文件队列
                      files = obj.pushFile();
                      //layer.load(); //上传loading
                      obj.preview(function (index, file, result) {
                          $(".layui-upload-list").append('<img src="' + result + '" id="remove_' + index + '" title="双击删除该图片" style="315px;height:435px;">') //预览图片大小
                          $('#remove_' + index).bind('dblclick', function () {//双击删除指定预上传图片
                              delete files[index];//删除指定图片
                              $(this).remove();
                          })
                          //console.log(1, index); //得到文件索引
                          //console.log(2, file.name); //得到文件对象
                          //console.log(3, result); //得到文件base64编码,比如图片
                      })
                  },
                  done: function (res) {
                      //imgs = imgs.concat(res.Data)
                      //console.log(imgs)
                      if (res.code==0) {
                          layer.msg("图片上传成功!", { icon: 1, time: 1000 },
                          //清空文件列表
                          function (){
                            for (let x in files) {
                                delete files[x];
                            }
                            $(".layui-upload-list").html(""); //清空div
                        });
                        if(res.msg=="null"){   
                            window.location.href="{% url 'successful' %}"     //结束跳转指定页面
                        }
                        if(res.msg!="null"){
                            $("#provename").attr("value",res.msg); //赋值input value
                            $("#provena").html(res.msg);  //赋值div
                        }
                      }
                      //上传完毕回调
                  },
                  error: function () {
                      //请求异常回调
                  }
              });
        });
        </script>
     
    后台
    import jsoni
    from django.http import JsonResponse
     
    def provee(request):
        if request.user.is_authenticated: #是否登录
            user = request.user.id
            if len(peoplesProfile.objects.filter(user_id=user))>0: #上一步信息是否填写
                people = peoplesProfile.objects.get(user_id=user)
                obj = information.objects.get(id=people.intention_id)  
                str = obj.provena  #获取标签内容  标签采用逗号分隔
                strlist = str.split(',')
                list = []      #新建列表用来存储标签
                for value in strlist:
                    list.append(value)  #标签分开存入列表
                if request.method =='GET':
                    texta = list[0]
                    if len(Prove.objects.filter(provePeople_id=user))>0:   #判断是否重复提交
                        Prove.objects.filter(provePeople_id=user).delete() #重复则删除原有的
                    return render(request,'first/proved.html',{'text':texta})
                if request.method =='POST':
                    com_from = request.META.get("HTTP_REFERER")
                    textb = request.POST.get('provename')  #获取额外参数
                    for f in request.FILES.getlist('file'):    #循环图片列表
                        pro = Prove()  
                        pro.provePeople = request.user
                        pro.proveName = textb         #打上标签
                        pro.provePhoto = f        #存入图片
                        pro.save()
                        a=0        #初始一个参数a
                    for text in list:     #循环列表
                        a=a+1
                        if text==textb:     #与前端获取标签相同时
                            if textb==list[len(list)-1]:    #是否为最后一个标签
                                textc = "null"
                                break
                            else:
                                textc = list[a]   #下一个标签 
                                break
                    return JsonResponse({'code': '0','msg': textc})    #json返回
            else:
                return redirect(reverse('home'))    
        else:
            return redirect(reverse('loginh'))
  • 相关阅读:
    Binary Tree Paths
    Implement Stack using Queues
    Path Sum II
    Path Sum
    Plus One
    Add Digits
    Missing Number
    H-Index II
    H-Index
    Ugly Number II
  • 原文地址:https://www.cnblogs.com/ddb1-1/p/12347697.html
Copyright © 2011-2022 走看看