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

一、form表单提交文件

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

 

 如何保存文件呢?

def index(request):
    if request.method=='POST':
        # print(request.POST)   #<QueryDict: {}>
        # print(request.FILES)   #<MultiValueDict: {'file': [<InMemoryUploadedFile: 123.jpg (image/jpeg)>]}>
        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")
可以传文件和数据一起传
<body> <form action="" method="post" enctype="multipart/form-data"> <p>username: <input type="text" name="username"> </p> <p> file: <input type="file" name="file"> </p> <input type="submit" value="提交"> </form> </body>

 

 

posted @ 2021-11-25 20:53  甜甜de微笑  阅读(110)  评论(0编辑  收藏  举报