urls.py
from django.urls import pathfrom test01 import viewsurlpatterns = [ path('index/',views.index.as_view(),name='index'),]
html
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>网页上传</title></head><body><h1> 欢迎使用网页上传文件 </h1> <form action="{{ url }}" method="post" enctype="multipart/form-data"> {# 如果不用form_data格式来发,那么默认的是urlencoded的格式,这个标签的数据会组成avatar:文件名字来进行发送#} {% csrf_token %} 用户名: <input type="text" name="user"> 头像: <input type="file" name="head-png"> <input type="submit"> </form></body></html>
views.py
import os.pathfrom django.shortcuts import render,HttpResponse,redirectfrom django.views import Viewfrom django.conf import settings# Create your views here.class index(View): html = 'h5_upload_file.html' def get(self,request): # print(request.GET) # <QueryDict: {}> GET请求数据 return render(request,self.html) def post(self,request): user = request.POST.get('user') file_obj = request.FILES.get('head-png') # 获取文件 file_name = os.path.join(settings.BASE_DIR,'img',file_obj.name) # project/img/filename with open(file_name,'wb') as f: #不能一下写进去,占用的内容太多,要一点一点写 for i in file_obj: f.write(i) # 每次读取的data不是固定长度的,和读取其他文件一样,每次读一行,识别符为\r \n \r\n,遇到这几个符号就算是读了一行 return HttpResponse('ok')
