基于form表单提交
# 需要指定form-data,不能直接拼键值对
可以指定name照片存在位置
views.py
from django.shortcuts import render,redirect,HttpResponse # Create your views here. import os def index(request): if request.method=="POST": print(request.POST) # post里面只放键值对 # < QueryDict: {‘csrfmiddlewaretoken‘: # [‘hS5bYNIkbNqazL7svWKxwrJXXY5sftIR1mxrMUMqox9diZS4bwz7Nn183Um8H0U8‘], ‘user‘: [‘6666‘], ‘f‘: [‘vzh.jpg‘]} > print(request.FILES) # <MultiValueDict: {‘f‘: [<InMemoryUploadedFile: vzh.jpg (image/jpeg)>]}> obj = request.FILES.get("f") # 取出上传文件的对象 name = obj.name # 具体文件的名字 f_write = open(os.path.join("app01","static","img",name),"wb") # 如果想要将文件存在某个具体的位置,将路径拼接出来,再加上name # 如果只放name ,那么文件会存在当前的根目录下 for line in obj: # 取出每一行的数据 f_write.write(line) return HttpResponse("111") return render(request,"index.html") def put(request): return HttpResponse("ok")
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Title</title> </head> <body> <h3>基于form表单上传文件</h3> {# form-data类型可以上传文件#} <form action="" method="post" ENCTYPE="multipart/form-data"> {% csrf_token %} <p><input type="text" name="user"></p> <p><input type="file" name="f"></p> <input type="submit"> </form> </body> </html>
注意点:
form表单 <form action="" method="post" ENCTYPE="multipart/form-data"> 需要加ENCTYPE="multipart/form-data" form-data是可以用来上传文件