文件上传
实现步骤
配置URL
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^student/', include('student.urls')),
]
#coding=utf-8
from django.conf.urls import url
from . import views
urlpatterns=[
url(r'^$', views.Index.as_view()),
]
创建视图
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
# Create your views here.
from django.views import View
class Index(View):
def get(self,request):
return render(request,'index.html')
def post(self,request):
uname = request.POST.get('uname','')
photo = request.FILES.get('photo','')
import os
if not os.path.exists('static'):
os.makedirs('static')
with open(os.path.join(os.getcwd(),'static',photo.name),'wb') as fw:
#分块读取
for chunk in photo.chunks():
fw.write(chunk)
#一次性读取
#read=photo.read()
#fw.write(read)
return HttpResponse('上传成功!')
-
photo.read():从文件中读取整个上传的数据,这个方法只适合小文件;
-
photo.chunks():按块返回文件,通过在for循环中进行迭代,可以将大文件按块写入到服务器中;
-
photo.multiple_chunks():这个方法根据myFile的大小,返回True或者False,当myFile文件大于2.5M(默认为2.5M,可以调整)时,该方法返回True,否则返回False,因此可以根据该方法来选择选用read方法读取还是采用chunks方法
-
photo.name:这是一个属性,不是方法,该属性得到上传的文件名,包括后缀,如123.exe;
-
photo.size:这也是一个属性,该属性得到上传文件的大小。
创建模板
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/student/" method="post" enctype="multipart/form-data">
{% csrf_token %}
用户名:<input type="text" name="uname"/><br/><br/>
头 像:<input type="file" name="photo"/><br/><br/>
    <input type="submit" value="注册"/>
</form>
</body>
</html>