html页面代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<!DOCTYPE html> < html lang = "en" >
< head >
< meta charset = "UTF-8" >
< title >Title</ title >
</ head >
< body >
< form enctype = "multipart/form-data" action = "/app01/upload/" method = "POST" >
{% csrf_token %}
< input type = "file" name = "upload" />
< br />
< input type = "submit" value = "上传" />
</ form >
</ body >
</ html >
|
URL配置:
1
2
3
|
urlpatterns = [,
url(r '^upload/$' , upload),
] |
views.py配置:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
def upload(request):
if request.method = = 'GET' :
return render(request, 'upload.html' )
elif request.method = = 'POST' :
content = request.FILES.get( "upload" , None )
if not content:
return HttpResponse( "没有上传内容" )
position = os.path.join( 'C:\\Users\\huyuan\\Desktop\\test\\upload' ,content.name)
#获取上传文件的文件名,并将其存储到指定位置
storage = open (position, 'wb+' ) #打开存储文件
for chunk in content.chunks(): #分块写入文件
storage.write(chunk)
storage.close() #写入完成后关闭文件
return HttpResponse( "上传成功" ) #返回客户端信息
else :
return HttpResponseRedirect( "不支持的请求方法" )
|
上传文件的常用方法和属性:
content.read():从文件中读取整个上传的数据,这个方法只适合小文件
content.chunks():按块写入文件,通过for循环可以将大文件按块写入到磁盘中
content.name:获取文件名,包括后缀
content.size:获取文件大小
本文转自 红尘世间 51CTO博客,原文链接:http://blog.51cto.com/hongchen99/1954705