Django--上传文件
需求
Django中forms表单上传文件处理
速查
views.py
1 2 3 4 5 6 7 8 9 | def upload(request): if request.method = = 'POST' : inp_files = request.FILES file_obj1 = inp_files.get( 'f1' ) f = open (file_obj1.name, 'wb' ) for line in file_obj1.chunks(): f.write(line) f.close() return render(request, 'home/upload.html' ) |
知识点
- 上传文件是必须加上:enctype="multipart/form-data",代表分片传输。
request.FILES是上传的文件,获取某个文件,是get那个name属性名。
obj.name获取文件名,obj.size获取文件大小。
obj.chunks()是上传文件的所有分片集合,循环每一个分片,write写入文件。
详细
templates/home/upload.html
1 2 3 4 5 6 | < form action = "/upload/" method = "POST" enctype = "multipart/form-data" > < p >< input type = "file" name = "f1" /> </ p > < p >< input type = "file" name = "f2" /> </ p > < p >< input type = "text" name = "name" /> </ p > < input type = "submit" value = "Upload" /> </ form > |
app01/urls.py
1 2 3 4 | from app01.views import home urlpatterns = [ url(r '^upload/' , home.upload), ] |
app01/views/home.py
1 2 3 4 5 6 7 8 9 | def upload(request): if request.method = = 'POST' : inp_files = request.FILES file_obj1 = inp_files.get( 'f1' ) f = open (file_obj1.name, 'wb' ) for line in file_obj1.chunks(): f.write(line) f.close() return render(request, 'home/upload.html' ) |
browser
传输的位置如果没指定,默认是项目的 “/”根目录。