上传文件

1、Form表单上传

    obj = request.FILES.get('xxx')

    obj.read():从文件中读取整个上传的数据,这个方法只适合小文件;

    obj.chunks():按块返回文件,通过在for循环中进行迭代,可以将大文件按块写入到服务器中;  

    obj.multiple_chunks():这个方法根据myFile的大小,返回True或者False,当myFile文件大于2.5M(默认为2.5M,可以调整)时,该方法返回True,否则返回False,因此可以根据该方法来选择选用read方法读取还是采用chunks方法

    obj.name:这是一个属性,不是方法,该属性得到上传的文件名,包括后缀,如123.exe;

    obj.size:这也是一个属性,该属性得到上传文件的大小。

from django.db import models
class Img(models.Model):
    path = models.CharField(max_length=128)
models.py
from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
        url(r'^admin/', admin.site.urls),
        url(r'^upload.html$', views.upload),
]
urls.py
 1 from django.shortcuts import render,redirect,HttpResponse
 2 from app01 import models
 3 import os
 4 def upload(request):
 5     if request.method == 'GET':
 6         img_list = models.Img.objects.all()
 7         return render(request,'upload.html',{'img_list': img_list})
 8     elif request.method == "POST":
 9         user = request.POST.get('user')
10         fafafa = request.POST.get('fafafa')
11         obj = request.FILES.get('fafafa')
12 
13         file_path = os.path.join('static','upload',obj.name)
14         f = open(file_path, 'wb')
15         for chunk in obj.chunks():
16             f.write(chunk)
17         f.close()
18 
19         models.Img.objects.create(path=file_path)
20 
21         return redirect('/upload.html')
views.py
 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6 </head>
 7 <body>
 8     <form method="POST" action="/upload.html" enctype="multipart/form-data">
 9         <input type="text" name="user" />
10         <input type="file" name="fafafa" />
11         <input type="submit" value="提交" />
12     </form>
13 
14     <div>
15         {% for item in img_list %}
16             <img style="height: 200px;width: 200px;" src="/{{ item.path }}" />
17         {% endfor %}
18     </div>
19 
20 </body>
21 </html>
HTML

    缺点:上传后整个页面会刷新,不好

2、基于FormData实现文件上传(XMLHttpRequest和jQuery)

    利用FormData对象,我们可以通过JavaScript用一些键值对来模拟一系列表单控件,比起普通的ajax,使用FormData的最大优点就是我们可以异步上传一个二进制文件.

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4   <meta charset="UTF-8">
 5   <title>Title</title>
 6   <style>
 7       .container img{
 8           width: 200px;
 9           height: 200px;
10       }
11   </style>
12 </head>
13 <body>
14   <input ID="v1" name="user" placeholder="用户">
15   <input type="file" name="fafafa" id="img" />
16   <input type="button" value="提交XML" onclick="UploadXML()" />
17   <input type="button" value="提交JQ" onclick="Uploadjq()" />
18   <div id="imgs">
19 
20   </div>
21 </body>
22   <script src="/static/jquery-2.1.4.min.js"></script>
23   <script>
24       function UploadXML() {
25           var dic = new FormData();
26           dic.append(‘user‘, $(‘#v1‘).val());
27           dic.append(‘fafafa‘, document.getElementById(‘img‘).files[0]);
28 
29           var xml = new XMLHttpRequest();
30           xml.open(‘post‘, ‘/upload.html‘, true);
31           xml.onreadystatechange = function () {
32               if(xml.readyState == 4){
33                   var obj = JSON.parse(xml.responseText);
34                   console.log(obj)
35                   if(obj.status){
36                       var img = document.createElement(‘img‘);
37                       img.src = "/" + obj.path;
38                       document.getElementById("imgs").appendChild(img);
39                   }
40               }
41           };
42           xml.send(dic);
43       }
44       function Uploadjq() {
45           var dic = new FormData();
46           dic.append(‘user‘, $(‘#v1‘).val());
47           dic.append(‘fafafa‘, document.getElementById(‘img‘).files[0]);
48 
49           $.ajax({
50               url: ‘/upload.html‘,
51               type: ‘POST‘,
52               data: dic,
53               processData: false,  // tell jQuery not to process the data
54               contentType: false,  // tell jQuery not to set contentType
55               dataType: ‘JSON‘,
56               success: function (arg) {
57                   if (arg.status){
58                       console.log("111")
59                       var img = document.createElement(‘img‘);
60                       img.src = "/" + arg.path;
61                       $(‘#imgs‘).append(img);
62                   }
63               }
64           })
65 
66       }
67   </script>
68 
69 </body>
70 </html>
71 
72 /////后台代码
73 from app01 import models
74 import json
75 
76 from django.shortcuts import render,HttpResponse
77 import os,json
78 def upload(request):
79   if request.method == ‘GET‘:
80       return render(request,‘upload.html‘)
81   elif request.method == "POST":
82       user = request.POST.get(‘user‘)
83       print(user)
84       fafafa = request.POST.get(‘fafafa‘)
85       obj = request.FILES.get(‘fafafa‘)
86 
87       file_path = os.path.join(‘static‘,‘upload‘,obj.name)
88       f = open(file_path, ‘wb‘)
89       for chunk in obj.chunks():
90           f.write(chunk)
91       f.close()
92       ret = {‘status‘: True, ‘path‘: file_path}
93       return HttpResponse(json.dumps(ret))
View Code

    实现了异步刷新,但是部分老版本的浏览器不支持FormData对象

3、基于iframe和form表单伪造ajax并实现文件上传

 1 一、表单提交的代码常规写法
 2 <iframe name="testIframeName" style="display:none;"></iframe>  
 3 <!--form表格的target属性的值对应上iframe的name属性值, 将form表单提交的窗口指向隐藏的ifrmae,并通过ifrmae提交数据。 -->
 4 <form target="testIframeName" method="post" action="xxxx.do">  
 5     <input type="text" name="username"/>  
 6     <input type="password" name="password"/>  
 7     <input type="submit" value=" 提 交 " />  
 8 </form>
 9 二、替换成全部隐藏的代码写法
10 $("#downLoadIFrame").remove();
11 var $Iframe = $("<iframe>");
12 $Iframe.attr("name", "downLoadIFrame");
13 $Iframe.attr("id", "downLoadIFrame");
14 $Iframe.attr("style", "diaplay:none");
15 $("body").append($Iframe);
16 var $form = $("<form>");
17 $form.empty();
18 $form.attr("style", "diaplay:none");
19 $form.attr("target", "downLoadIFrame"); // 对应iframe的name属性值
20 $form.attr("method", "post");
21 $form.attr("action", "xxxxx.do"); // 指向后端请求链接
22 $("body").append($form);
23 
24 // 新建input, 并设置name属性和value的值
25 var $input = $("<input>");
26 $input.attr("type", "hidden");
27 $input.attr("name", "xyz"); // 填上后台对应的name字段
28 $input.attr("value", "xxxxxyyyyzzzz"); // 填上传的值
29 $form.append($input);
30 
31 $form.submit();
32 
33 // 监听iframe回调
34 $Iframe.on("load", function() {
35     var contentWin = document.getElementById("downLoadIFrame").contentWindow;
36     var backBodyText = contentWin.document.body.innerText;
37 
38     $Iframe.remove();
39 });
40 $Iframe.remove();
iframe使用方法

    jQuery Ajax上传,同时使用了iframe,一下代码包含了两种方法。即:

           (1)-利用JQuery Ajax + FormData进行文件上传
           (2)-基于Iframe实现伪Ajax 上传文件

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4   <meta charset="UTF-8">
 5   <title>Title</title>
 6   <style>
 7       .container img{
 8           width: 200px;
 9           height: 200px;
10       }
11   </style>
12 </head>
13 <body>
14   <h1>基于iframe实现form提交</h1>
15   <form action="/upload.html" method="post" target="iframe_1" enctype="multipart/form-data">
16       <iframe style="display: none"  id="iframe_1" name="iframe_1" src="" onload="loadIframe();"></iframe>
17       <input type="text" name="user" /><br>
18       <input type="file" name="fafafa" />
19       <input type="submit" value="提交" />
20   </form>
21   <div id="imgs">
22 
23   </div>
24 </body>
25   <script src="/static/jquery-2.1.4.min.js"></script>
26   <script>
27       function loadIframe() {
28           console.log(1);
29           // 获取iframe内部的内容
30           var str_json = $(‘#iframe_1‘).contents().find(‘body‘).text();
31           var obj = JSON.parse(str_json);
32           if (obj.status){
33               var img = document.createElement(‘img‘);
34               img.src = "/" + obj.path;
35               $(‘#imgs‘).append(img);
36           }
37       }
38   </script>
39 
40 </body>
41 </html>
42 ///后台代码
43 from django.shortcuts import render,HttpResponse
44 import os,json
45 def upload(request):
46   if request.method == ‘GET‘:
47       return render(request,‘upload.html‘)
48   elif request.method == "POST":
49       user = request.POST.get(‘user‘)
50       print(user)
51       fafafa = request.POST.get(‘fafafa‘)
52       obj = request.FILES.get(‘fafafa‘)
53 
54       file_path = os.path.join(‘static‘,‘upload‘,obj.name)
55       f = open(file_path, ‘wb‘)
56       for chunk in obj.chunks():
57           f.write(chunk)
58       f.close()
59 
60       ret = {‘status‘: True, ‘path‘: file_path}
61 
62       return HttpResponse(json.dumps(ret))
View Code
 1 1、首先写一个iframe
 2 
 3 <iframe name="myiframe" style="display:none;" onload="iframeLoad(this)"></iframe>
 4 
 5 2、创建文件上传的form,form的target属性值和iframe的name一致
 6 
 7 <form id="upload" action="${webRoot }/tlTrialCalculation/doImport"  method="post"  enctype="multipart/form-data" target="myiframe">
 8     <input type="hidden" name="processId" value="${processId }">
 9     <input id="upload" type="file" name="file" size="28" onChange="uploadFile()" accept="image/jpeg,image/png"/>
10 </form>
11 
12 3、为文件按钮编写onChange事件触发的方法
13 
14 function uploadFile(){
15 
16 $('#upload).submit();
17 
18 }
19 
20 4、编写iframe的加载完成方法,在这里处理上传成功后的操作
21 
22 function iframeLoad(ifame){
23 
24 var doc = iframe.contentWindow.document; 
25 var html = doc.body.innerHTML;
26 
27 html
28 
29 }
具体步骤

附:上传文件按钮美化示例

 1 input file上传按钮的美化思路是,先把之前的按钮透明度opacity设置为0,然后,外层用a标签或其他标签包裹,就实现了美化功能
 2 <!DOCTYPE html>
 3 <html lang="en">
 4 <head>
 5     <meta charset="UTF-8">
 6     <title>Title</title>
 7     <style>
 8         .a-upload {
 9             position: relative;
10             display: inline-block;
11             height: 30px;
12             line-height: 30px;
13             background-color: darkblue;
14             color: white;
15             text-decoration: none;
16             border-radius: 20%;
17             border: 1px solid #ddd;
18             overflow: hidden;
19             padding: 0 10px;
20             margin: 10px;
21         }
22         .a-upload input {
23             position: absolute;
24             opacity: 0;
25             cursor: pointer;
26             filter: alpha(opacity=0);
27             right: 0;
28         }
29     </style>
30 </head>
31 <body>
32 <form enctype="multipart/form-data">
33     <a href="javascript:" class="a-upload">
34         <input type="file" name="" id="">上传
35     </a>
36 </form>
37 </body>
38 </html>
上传文件按钮美化示例

 

other example:https://www.cnblogs.com/wupeiqi/articles/5702910.html

 1 <!DOCTYPE html>
 2 <html>
 3 <head lang="en">
 4     <meta charset="UTF-8">
 5     <title></title>
 6 </head>
 7 <body>
 8     <input type="file" id="img" />
 9     <input type="button" onclick="UploadFile();" />
10     <script>
11         function UploadFile(){
12             var fileObj = document.getElementById("img").files[0];
13 
14             var form = new FormData();
15             form.append("k1", "v1");
16             form.append("fff", fileObj);
17 
18             var xhr = new XMLHttpRequest();
19             xhr.open("post", '/index', true);
20             xhr.send(form);
21         }
22     </script>
23 </body>
24 </html>
HTML - XMLHttpRequest
 1 <!DOCTYPE html>
 2 <html>
 3 <head lang="en">
 4     <meta charset="UTF-8">
 5     <title></title>
 6 </head>
 7 <body>
 8     <input type="file" id="img" />
 9     <input type="button" onclick="UploadFile();" />
10     <script>
11         function UploadFile(){
12             var fileObj = $("#img")[0].files[0];
13             var form = new FormData();
14             form.append("k1", "v1");
15             form.append("fff", fileObj);
16 
17             $.ajax({
18                 type:'POST',
19                 url: '/index',
20                 data: form,
21                 processData: false,  // tell jQuery not to process the data
22                 contentType: false,  // tell jQuery not to set contentType
23                 success: function(arg){
24                     console.log(arg);
25                 }
26             })
27         }
28     </script>
29 </body>
30 </html>
HTML - jQuery
 1 <!DOCTYPE html>
 2 <html>
 3 <head lang="en">
 4     <meta charset="UTF-8">
 5     <title></title>
 6 </head>
 7 <body>
 8     <form id="my_form" name="form" action="/index" method="POST"  enctype="multipart/form-data" >
 9         <div id="main">
10             <input name="fff" id="my_file"  type="file" />
11             <input type="button" name="action" value="Upload" onclick="redirect()"/>
12             <iframe id='my_iframe' name='my_iframe' src=""  class="hide"></iframe>
13         </div>
14     </form>
15 
16     <script>
17         function redirect(){
18             document.getElementById('my_iframe').onload = Testt;
19             document.getElementById('my_form').target = 'my_iframe';
20             document.getElementById('my_form').submit();
21 
22         }
23         
24         function Testt(ths){
25             var t = $("#my_iframe").contents().find("body").text();
26             console.log(t);
27         }
28     </script>
29 </body>
30 </html>
HTML - iframe
 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 
 4 import tornado.ioloop
 5 import tornado.web
 6 
 7 
 8 class MainHandler(tornado.web.RequestHandler):
 9     def get(self):
10 
11         self.render('index.html')
12 
13     def post(self, *args, **kwargs):
14         file_metas = self.request.files["fff"]
15         # print(file_metas)
16         for meta in file_metas:
17             file_name = meta['filename']
18             with open(file_name,'wb') as up:
19                 up.write(meta['body'])
20 
21 settings = {
22     'template_path': 'template',
23 }
24 
25 application = tornado.web.Application([
26     (r"/index", MainHandler),
27 ], **settings)
28 
29 if __name__ == "__main__":
30     application.listen(8000)
31     tornado.ioloop.IOLoop.instance().start()
Python
 1 <script type="text/javascript">
 2  
 3     $(document).ready(function () {
 4  
 5         $("#formsubmit").click(function () {
 6  
 7             var iframe = $('<iframe name="postiframe" id="postiframe" style="display: none"></iframe>');
 8  
 9             $("body").append(iframe);
10  
11             var form = $('#theuploadform');
12             form.attr("action", "/upload.aspx");
13             form.attr("method", "post");
14  
15             form.attr("encoding", "multipart/form-data");
16             form.attr("enctype", "multipart/form-data");
17  
18             form.attr("target", "postiframe");
19             form.attr("file", $('#userfile').val());
20             form.submit();
21  
22             $("#postiframe").load(function () {
23                 iframeContents = this.contentWindow.document.body.innerHTML;
24                 $("#textarea").html(iframeContents);
25             });
26             return false;
27         });
28     });
29  
30 </script>
31  
32 <form id="theuploadform">
33     <input id="userfile" name="userfile" size="50" type="file" />
34     <input id="formsubmit" type="submit" value="Send File" />
35 </form>
36  
37 <div id="textarea">
38 </div>
扩展:基于iframe实现Ajax上传示例
$('#upload_iframe').load(function(){
                    var iframeContents = this.contentWindow.document.body.innerText;
                    iframeContents = JSON.parse(iframeContents);
                   
                })
View Code
 1 function bindChangeAvatar1() {
 2             $('#avatarImg').change(function () {
 3                 var file_obj = $(this)[0].files[0];
 4                 $('#prevViewImg')[0].src = window.URL.createObjectURL(file_obj)
 5             })
 6         }
 7 
 8         function bindChangeAvatar2() {
 9             $('#avatarImg').change(function () {
10                 var file_obj = $(this)[0].files[0];
11                 var reader = new FileReader();
12                 reader.readAsDataURL(file_obj);
13                 reader.onload = function (e) {
14                     $('#previewImg')[0].src = this.result;
15                 };
16             })
17         }
18 
19         function bindChangeAvatar3() {
20             $('#avatarImg').change(function () {
21                 var file_obj = $(this)[0].files[0];
22                 var form = new FormData();
23                 form.add('img_upload', file_obj);
24 
25                 $.ajax({
26                     url: '',
27                     data: form,
28                     processData: false,  // tell jQuery not to process the data
29                     contentType: false,  // tell jQuery not to set contentType
30                     success: function (arg) {
31 
32                     }
33                 })
34             })
35         }
36 
37         function bindChangeAvatar4() {
38             $('#avatarImg').change(function () {
39                 $(this).parent().submit();
40 
41                 $('#upload_iframe').load(function () {
42                     var iframeContents = this.contentWindow.document.body.innerText;
43                     iframeContents = JSON.parse(iframeContents);
44                     if (iframeContents.status) {
45                         $('#previewImg').attr('src', '/' + iframeContents.data);
46                     }
47                 })
48 
49             })
50         }
其他
posted on 2019-06-02 20:16  始终不够啊  阅读(212)  评论(0编辑  收藏  举报