20 django视图层之(form表单传文件)


一、form表单提交文件

1.method必须是post
2.enctype参数必须是multipart/form-data  (如果你把编码格式改成formdata,那么针对普通的键值对还是解析到request.POST中,将文件解析到request.FILES中
    request.POST无法获取到文件类型的数据
    request.FILES获取文件类型的数据
 
前端获取文件数据
    "file" name="file">  只能获取一个
    "file" name="file" multiple>  可以一次性获取多个
 
后端获取文件数据
    request.FILES.get()
    request.FILES.getlist()

 如何保存文件呢?

def index(request):
    if request.method=='POST':
        # print(request.POST)   #
        # print(request.FILES)   #]}>
        file_obj=request.FILES.get("file")
        print(file_obj.name) #获取文件名
        with open(file_obj.name,'wb') as f: #打开一个空文件
            for line in file_obj:  #一行一行读文件内容并写入空文件
                f.write(line)
    return render(request,"index.html")
可以传文件和数据一起传
"" method="post" enctype="multipart/form-data">

username: "text" name="username">

file: "file" name="file">

"submit" value="提交">