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> # &#x6307;&#x5B9A;type&#x4E3A;file
    <p><input type="submit" class="btn btn-primary"></p>
</form>

后端获取文件

def index(request):
    if request.method == 'POST':
        print(request.FILES)
        # &#x83B7;&#x53D6;&#x5230;&#x7684;&#x6587;&#x4EF6;&#x6570;&#x636E; <multivaluedict: {'file': [<inmemoryuploadedfile: 证件照.jpg (image jpeg)>]}>
        file_obj = request.FILES.get('file')  # &#x83B7;&#x53D6;&#x7684;&#x662F;&#x6587;&#x4EF6;&#x5BF9;&#x8C61;
        print(file_obj.name) # &#x83B7;&#x53D6;&#x5F53;&#x524D;&#x6587;&#x4EF6;&#x7684;&#x540D;&#x5B57;
        with open(file_obj.name,'wb') as f: # &#x6253;&#x5F00;file_obj.name&#x6587;&#x4EF6;&#x5199;&#x5165;&#x6587;&#x4EF6;
            for line in file_obj:
                f.write(line)
    return render(request,'file.html')
</multivaluedict:>

Original: https://www.cnblogs.com/suncolor/p/16663447.html
Author: 等日落
Title: form表单上传文件及后端获取文件

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/611424/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球