框架----Django之文件上传

Posted ForeverPine

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了框架----Django之文件上传相关的知识,希望对你有一定的参考价值。

一、文件上传

1. 浏览器访问

http://127.0.0.1:8000/f1/

http://127.0.0.1:8000/f2/

2. urls

from django.conf.urls import url
from django.contrib import admin
from app01 import views

urlpatterns = [
    url(r\'^admin/\', admin.site.urls),
    url(r\'^f1/\', views.f1),
    url(r\'^f2/\', views.f2),
]

3. views

 1 from django.shortcuts import render,redirect,HttpResponse
 2 from app01 import models
 3 from django.forms import Form
 4 from django.forms import fields
 5 from django.forms import widgets
 6 
 7 
 8 # **************************文件上传**************************
 9 def f1(request):
10     if request.method == "GET":
11         return render(request,\'f1.html\')
12     else:
13         import os
14         # request.POST
15         file_obj = request.FILES.get(\'fafafa\')
16         f = open(os.path.join(\'static\',file_obj.name),\'wb\')
17         for chunk in file_obj.chunks():
18             f.write(chunk)
19         f.close()
20         # return render(request,\'f1.html\')         # 上传成功后刷新当前页面
21         return HttpResponse(\'上传成功\')          # 上传完成后显示文字
22 
23 class F2Form(Form):
24     user = fields.CharField()
25     fafafa = fields.FileField()
26 
27 def f2(request):
28     if request.method == "GET":
29         obj = F2Form()
30         return render(request,\'f2.html\',{\'obj\':obj})
31     else:
32         obj = F2Form(data=request.POST,files=request.FILES)
33         if obj.is_valid():
34             print(obj.cleaned_data.get(\'fafafa\').name)
35             print(obj.cleaned_data.get(\'fafafa\').size)
36         return render(request,\'f2.html\',{\'obj\':obj})
views

4. templates

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title></title>
 6 </head>
 7 <body>
 8     <form method="POST" action="/f1/" enctype="multipart/form-data">
 9         {% csrf_token %}
10         <input type="text" name="user" />
11         <input type="file" name="fafafa" />
12         <input type="submit" value="提交" />
13     </form>
14 </body>
15 </html>
f1.html
 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title></title>
 6 </head>
 7 <body>
 8     <form method="POST" action="/f2/" enctype="multipart/form-data">         
 9         {# 不能少了这个属性:enctype="multipart/form-data" ,否则后台拿不到数据 #}
10         
11         {% csrf_token %}
12         {{ obj.user }}
13         {{ obj.fafafa }}
14         <input type="submit" value="提交" />
15     </form>
16 </body>
17 </html>
f2.html

 二、文件上传--------原生Ajax上传文件、jQuery Ajax上传文件、伪Ajax上传文件

1. 浏览器访问

http://127.0.0.1:8000/upload/

2. urls

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/\', views.upload),
]
View Code

3. views

 1 from django.shortcuts import render,HttpResponse,redirect
 2 
 3 import os
 4 def upload(request):
 5     if request.method == \'GET\':
 6         return render(request,\'upload.html\')
 7     else:
 8         print(request.POST,request.FILES)
 9         file_obj = request.FILES.get(\'fafafa\')
10         file_path = os.path.join(\'static\',file_obj.name)
11         with open(file_path,\'wb\') as f:
12             for chunk in file_obj.chunks():
13                 f.write(chunk)
14 
15         return HttpResponse(file_path)
views

4. templates

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title></title>
 6 </head>
 7 <body>
 8     <h1>原生Ajax上传文件</h1>
 9     <input type="file" id="i1" />
10     <a onclick="upload1();">上传</a>
11     <div id="container1"></div>
12 
13     <h1>jQuery Ajax上传文件</h1>
14     <input type="file" id="i2" />
15     <a onclick="upload2();">上传</a>
16     <div id="container2"></div>
17 
18     <h1>伪 Ajax上传文件</h1>
19     <form id="f1" method="POST" action="/upload/" target="ifr" enctype="multipart/form-data">
20         <iframe id="ifr" name="ifr" style="display: none"></iframe>
21         <input type="file" name="fafafa" />
22         <a onclick="upload3();">上传</a>
23     </form>
24     <div id="container3"></div>
25 
26     <script src="/static/jquery-1.12.4.js"></script>
27     <script>
28 
29         function upload1(){
30             var formData = new FormData();
31             formData.append(\'k1\',\'v1\');
32             formData.append(\'fafafa\',document.getElementById(\'i1\').files[0]);
33 
34             var xhr = new XMLHttpRequest();
35             xhr.onreadystatechange = function(){
36                 if(xhr.readyState == 4){
37                     var  file_path = xhr.responseText;
38                     var tag = document.createElement(\'img\');
39                     tag.src = "/"+ file_path;
40                     document.getElementById(\'container1\').appendChild(tag);
41 
42                 }
43             };
44             xhr.open(\'POST\',\'/upload/\');
45             xhr.send(formData);
46         }
47 
48         function upload2(){
49             var formData = new FormData();
50             formData.append(\'k1\',\'v1\');
51             // formData.append(\'fafafa\',document.getElementById(\'i1\').files[0]);
52             formData.append(\'fafafa\',$(\'#i2\')[0].files[0]);
53             // $(\'#i2\') -> $(\'#i2\')[0]
54             // document.getElementById(\'i1\') -> $(document.getElementById(\'i1\'))
55 
56             $.ajax({
57                 url: \'/upload/\',
58                 type: \'POST\',
59                 data: formData,
60                 contentType:false,
61                 processData:false,
62                 success:function(arg){
63                     var tag = document.createElement(\'img\');
64                     tag.src = "/"+ arg;
65                     $(\'#container2\').append(tag);
66                 }
67             })
68         }
69 
70          function upload3(){
71             document.getElementById(\'ifr\').onload = loadIframe;
72             document.getElementById(\'f1\').submit();
73 
74         }
75         function loadIframe(){
76             var content = document.getElementById(\'ifr\').contentWindow.document.body.innerText;
77              var tag = document.createElement(\'img\');
78             tag.src = "/"+ content;
79             $(\'#container3\').append(tag);
80         }
81     </script>
82 </body>
83 </html>
upload.html

5. 执行结果截图

 

 

 

以上是关于框架----Django之文件上传的主要内容,如果未能解决你的问题,请参考以下文章

Django框架 之 Form表单和Ajax上传文件

python Django之文件上传

Django Rest 框架和文件上传

django 开发之文件上传

Django Rest 框架文件上传

十七 Django框架,文件上传