Django 使用form组件对文件上传

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6 </head>
 7 <body>
 8 <form action="/upload/" method="post" enctype="multipart/form-data">
 9     {% csrf_token %}
10     <input type="text" name="user">
11     <input type="file" name="img">
12     <input type="submit" value="提交">
13 </form>
14 </body>
15 </html>
 1 def upload(request):
 2     if request.method == 'GET':
 3            return render(request,'upload.html')
 4     else:
 5         # print(request.POST)
 6         #print(request.FILES)
 7         user = request.POST.get('user')
 8         img = request.FILES.get('img')
 9        # print(img.name)
10        # print(img.size)
11 #chunks()数据块,数据是一块一块的拿来。
12         for chunk in img.chunks():
13             f =open(img.name,'wb')
14             f.write(chunk)
15             f.close()
16         return HttpResponse('ok')
from django.conf.urls import url
from django.contrib import admin
from app1 import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    # url(r'xuliehua/',views.xuliehua),
    url(r'upload/',views.upload),
]

 

posted @ 2019-12-06 14:41  y0um  阅读(340)  评论(0编辑  收藏  举报

新人优惠服务器