Django--上传文件
Posted 大亮头
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django--上传文件相关的知识,希望对你有一定的参考价值。
需求
Django中forms表单上传文件处理?
速查views.py
123456789 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()
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() |
知识点- 上传文件是必须加上:enctype="multipart/form-data",代表分片传输。
request.FILES是上传的文件,获取某个文件,是get那个name属性名。
obj.name获取文件名,obj.size获取文件大小。
obj.chunks()是上传文件的所有分片集合,循环每一个分片,write写入文件。
request.FILES是上传的文件,获取某个文件,是get那个name属性名。
obj.name获取文件名,obj.size获取文件大小。
obj.chunks()是上传文件的所有分片集合,循环每一个分片,write写入文件。
详细templates/home/upload.html
123456 <
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
1234 from
app01.views
import
home
urlpatterns
=
[
url(r
‘^upload/‘
, home.upload),
]
app01/views/home.py
123456789 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
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 > |
1 2 3 4 | from app01.views import home urlpatterns = [ url(r ‘^upload/‘ , home.upload), ] |
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‘ ) |
传输的位置如果没指定,默认是项目的 “/”根目录。?
以上是关于Django--上传文件的主要内容,如果未能解决你的问题,请参考以下文章
Alamofire 文件上传出现错误“JSON 文本未以数组或对象开头,并且允许未设置片段的选项”