文件上传

文件上传

基于教务系统写的

1.form表单select选择框数据左右移动

(1)数据查询:

 models.teacher.objects.filter(name="root") #查找name=root的数据
 models.teacher.objects.exclude(name="root")#查找name!=root的数据
 models.teacher.objects.filter(id__in=[1,2,3])#查找id在[1,2,3]的数据
 models.teacher.objects.exclude(id__in=[1,2,3])#查找id不在[1,2,3]的数据

(2)jQuery对象和DOM对象相互转换:

 var obj=document.getElementById('sel') //DOM对象
 $('obj') //DOM对象转换成JQuery对象
 $('#sel') //JQuery对象
 $('#sel')[0] //JQuery对象转换成DOM对象

(3)获取select中的信息:

select标签的Dom对象中有 selectedOptions (找到数据) appendTo (移走数据,移到想要移动的地方)

(4)实际操作代码:

 <!-- 前端代码块 -->
     <form action="/edit_teacher-{{ obj.id }}/" method="POST">
         <input style="display: none" type="text" id="nid" value="{{ obj.id }}"/>
         <p>
            老师姓名:<input name="name" type="text" value="{{ obj.teachername }}"/>
         </p>
         <p>
        已管理班级:
         <select id="sel" name="cls" multiple>
            {% for foo in obj_list %}
                 <option value="{{ foo.0 }}" selected="selected">{{ foo.1 }}</option>
            {% endfor %}
         </select>
        未管理班级:
         <select id="sels" multiple>
            {% for foo in cls_list %}
                 <option value="{{ foo.id }}">{{ foo.classname }}</option>
            {% endfor %}
         </select>
         </p>
         <div class="">
             <a id="add_cla" style="font-size: 30px;cursor: pointer">+</a>
             <a id="delete_cla" style="font-size: 30px;cursor: pointer">-</a>
         </div>
         <br><input type="submit" value="提交">
     </form>
 //js代码部分
     <script>
         $(function(){
             bindadd_cla();
             binddelete_cla();
             bindSubmit();
        });
         function  bindSubmit() {
             $("#submit_form").click(function(){
                 $('#sel').children().each(function(){
                     $(this).prop("selected",true);
                })
            })
        };
         function binddelete_cla(){
             $("#delete_cla").click(function(){
                 var options = $('#sel')[0].selectedOptions;
                 //$.each(options,function(k,v){ //each循环每次移动一个就立即停止了
                 //   $(v).appendTo("#sels");
                 //});
                 while (options.length>0){
                     $(options[0]).appendTo("#sels");
                };
            })
        };
         function bindadd_cla(){
             $("#add_cla").click(function(){
                 var options = $('#sels')[0].selectedOptions;
                 while (options.length>0){
                     $(options[0]).appendTo("#sel");
                };
            })
        };
     </script>
  #后端代码块
     if request.method == "GET":
         #已选择的教师的id
         obj = models.teacher.objects.get(id=nid)
         #获取当前老师已经管理的所有班级
         obj_list=obj.cls.all().values_list("classid","classname")#元组
         print(obj_list)
         #已经管理的班级的ID列表
         id_list = list(zip(*obj_list))[0] if obj_list else [] #三元运算
         #获取不包括已经管理的班级
         cls_list=models.classes.objects.exclude(classid__in=id_list)
         return render(request,"edit_teacher.html",{"obj":obj,"cls_list":cls_list,"obj_list":obj_list})

 

2.From表单上传文件

注:使用form表单上传文件时必须要在form标签中添加encty属性:enctype="multipart/form-data"

 <!-- 前端代码块 -->
 {% extends "index.html" %}
 {% block right %}
     <form action="/upload/" method="post" enctype="multipart/form-data" style="margin-top: 60px;margin-left: 10%">
        上传者:<input type="text" name="username" style="margin-top: 20px;"><br>
         <input type="file" name="files" style="margin-top: 20px;"><br>
         <input type="submit" value="提交" style="margin-top: 20px;">
     </form>
     <div class="show" style="margin-top: 30px;margin-left: 10%;overflow: hidden">
         <h3>文件展示</h3>
        {% for foo in img_list %}
             <div class="files" style="float: left;margin-left: 8px;">
                 <p>filter:{{ foo.filter }}</p>
                 <p><img src="/{{ foo.path }}" style=" 100px;height: 100px"/><p>
             </div>
        {% endfor %}
     </div>
 {% endblock %}
 //数据库代码块
 class teacher(models.Model):
    teachername=models.CharField(max_length=64)
    cls = models.ManyToManyField('Classes')
 #文件上传(Form表单)
 def upload(request):
     if request.method == "GET":
         img_list = models.imagesurl.objects.all()
         return render(request,"upload.html",{"img_list":img_list})
     elif request.method == "POST":
         username = request.POST.get("username",None)
         #filesname = request.POST.get("files")
         file = request.FILES.get("files")
         import os
         path = os.path.join('statics', 'upload', file.name)
         f = open(path,'wb')
         for chunk in file.chunks():
             f.write(chunk)
         f.close()
         models.imagesurl.objects.create(filter=username,path=path)
         return redirect("/upload/")

3.Ajax上传文件(FromData——(JQuery,XMLHttpRequest))

 <!-- 前端代码块 -->
 {% extends "index.html" %}
 {% block right %}
     <div class="upload" style="margin-top: 60px;margin-left: 10%">
        上传者:<input type="text" name="username" style="margin-top: 20px;"><br>
         <input type="file" id="upfile" style="margin-top: 20px;"><br>
         <input type="button" value="XML提交" style="margin-top: 20px;" onclick="bindxml()">
         <input type="button" value="ajax提交" style="margin-top: 20px;" onclick="bindjq()">
     </div>
    <div class="show" id="show" style="margin-top: 30px;margin-left: 10%;overflow: hidden">
         <h3>FormData文件展示(xmlhttprequest和jquery)</h3>
        {% for foo in img_list %}
             <div class="files" id="images" style="float: left;margin-left: 8px;">
                 <p>filter:{{ foo.filter }}</p>
                 <p><img src="/{{ foo.path }}" style=" 100px;height: 100px"/><p>
             </div>
        {% endfor %}
     </div>
     <script>
         //XMLReques方式(原生ajax)
         function bindxml(){
             var dic = new FormData();
             //console.log(user);
             //alert(user);
             var user=document.getElementsByName('username')[0].value;
             //alert(user);
             //console.log(user);
             dic.append('username',user);
             dic.append('files',document.getElementById('upfile').files[0]);
             var xml = new XMLHttpRequest();
             xml.open('post','/uploadformdata/',true);
             xml.onreadystatechange = function(){
                 if(xml.readyState == 4){
                     var obj = JSON.parse(xml.responseText);
                     if(obj.status){
                         //console.log(obj.path);
                         var img = document.createElement('img');
                         img.src = "/"+obj.path;
                         img.style = " 100px;height: 100px";
                         document.getElementById("images").appendChild(img);
                    }
                }
            };
             xml.send(dic);
        };
         //JQuery(封装ajax)
         function bindjq(){
             var dic = new FormData();
             var user=document.getElementsByName('username')[0].value;
             dic.append('username',user);
             dic.append('files',document.getElementById('upfile').files[0]);
             $.ajax({
                 url:"/uploadformdata/",
                 type:"post",
                 processData:false,//不需要取设置请求头
                 contentType:false,//不需要进行任何数据处理
                 data:dic,
                 dataType:"json",
                 success:function(ret){
                     if(ret.status){
                         var img = document.createElement('img');
                         img.src = "/" +ret.path;
                         img.style = "margin-left:10px;margin-top:52px; 100px;height: 100px";
                         $("#show").append(img);
                    }
                }
            })
        };
     </script>
 
 {% endblock %}
 //数据库代码块
 class imagesurl(models.Model):
    filter = models.CharField(max_length=64)
    path = models.CharField(max_length=64)
 #后端代码块
 #文件上传(FormData)
 def uploadformdata(request):
     if request.method == "GET":
         img_list = models.imagesurl.objects.all()
         return render(request,"uploadformdata.html",{"img_list":img_list})
     elif request.method == "POST":
         username = request.POST.get("username",None)
         #filesname = request.POST.get("files")
         file = request.FILES.get("files")
         import os
         path = os.path.join('statics', 'upload', file.name)
         f = open(path,'wb')
         for chunk in file.chunks():
             f.write(chunk)
         f.close()
         models.imagesurl.objects.create(filter=username,path=path)
         ret = {'status':True,'path':path}
         return HttpResponse(json.dumps(ret))

4.基于form表单和iframe自己实现ajax请求(ifram伪造ajax请求)

注:jsonp本质创建script标签动态加载路径的链接然后再动态的删除(不会刷新页面)

 <!-- 前端代码块 -->
 {% extends "index.html" %}
 {% block right %}
     <h2 style="margin-top: 60px;margin-left: 10%">基于iframe的文件上传(实现From文件上传)</h2>
     <div class="upload" style="margin-top: 30px;margin-left: 10%">
         <form action="/uploadiframe/" method="post" target="iframe_s" enctype="multipart/form-data">
             <iframe id="iframe_s" name="iframe_s" onload="iframeurlsp()" style="display: none"></iframe>
            上传者:<input type="text" name="username" style="margin-top: 20px;">
             <input type="file" id="upfile" name="files" style="margin-top: 20px;">
             <input type="submit" value="提交">
         </form>
     </div>
     <div class="show" id="show" style="margin-top: 30px;margin-left: 10%;overflow: hidden">
         <h3>FormData文件展示(xmlhttprequest和jquery)</h3>
        {% for foo in img_list %}
             <div class="files" id="images" style="float: left;margin-left: 8px;">
                 <p>filter:{{ foo.filter }}</p>
                 <p><img src="/{{ foo.path }}" style=" 100px;height: 100px"/><p>
             </div>
        {% endfor %}
     </div>
     <script>
         function iframebutton(){
             //var urladdress = $("#upfile").val();
             //$("#urlsadd").attr("src",urladdress);
        };
         function iframeurlsp(){
             console.log(1);
             //获取iframe的内容
             var str_json = $("iframe").contents().find("body").text(); //$("iframe").contents().find("body").html()
             var obj = JSON.parse(str_json);
             if (obj.status){
                 var img = document.createElement('img');
                 img.src = "/" + obj.path;
                 img.style = "margin-left:10px;margin-top:52px; 100px;height: 100px";
                 $('#show').append(img);
            }
        };
     </script>
 {% endblock %}
 #后端代码块
 def uploadiframe(request):
     if request.method == "GET":
         img_list = models.imagesurl.objects.all()
         return render(request,"uploadiframe.html",{"img_list":img_list})
     elif request.method == "POST":
         username = request.POST.get("username",None)
         file = request.FILES.get("files")
         print(username,file)
         import os
         path = os.path.join('statics', 'upload', file.name)
         f = open(path,'wb')
         for chunk in file.chunks():
             f.write(chunk)
         f.close()
         models.imagesurl.objects.create(filter=username,path=path)
         ret = {'status':True,'path':path}
         return HttpResponse(json.dumps(ret))
 

 

原文地址:https://www.cnblogs.com/wylshkjj/p/11949983.html