form表单上传文件及后端获取文件

写在前面(强调)

使用form表单上传文件时必须要干的两件事:

1.form表单的method指定为post

2.指定enctype="multipart/form-data"

form表单上传文件

<form action="" method="post" enctype="multipart/form-data">
    <p class="form-control">uesrname:<input type="text" name="username" class="form-control"></p>
    <p>password:<input type="text" name="password" class="form-control"></p>
    <p>file:<input type="file" name="file" class="form-control"></p> # 指定type为file
    <p><input type="submit" class="btn btn-primary"></p>
</form>

后端获取文件

def index(request):
    if request.method == 'POST':
        print(request.FILES)
        # 获取到的文件数据 <MultiValueDict: {'file': [<InMemoryUploadedFile: 证件照.jpg (image/jpeg)>]}>
        file_obj = request.FILES.get('file')  # 获取的是文件对象
        print(file_obj.name) # 获取当前文件的名字
        with open(file_obj.name,'wb') as f: # 打开file_obj.name文件写入文件
            for line in file_obj:
                f.write(line)
    return render(request,'file.html')
posted @ 2022-09-06 22:01  等日落  阅读(1008)  评论(0编辑  收藏  举报