urls.py

  1. from django.urls import path
  2. from test01 import views
  3. urlpatterns = [
  4. path('index/',views.index.as_view(),name='index'),
  5. ]

html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>网页上传</title>
  6. </head>
  7. <body>
  8. <h1> 欢迎使用网页上传文件 </h1>
  9. <form action="{{ url }}" method="post" enctype="multipart/form-data"> {# 如果不用form_data格式来发,那么默认的是urlencoded的格式,这个标签的数据会组成avatar:文件名字来进行发送#}
  10. {% csrf_token %}
  11. 用户名: <input type="text" name="user">
  12. 头像: <input type="file" name="head-png">
  13. <input type="submit">
  14. </form>
  15. </body>
  16. </html>

views.py

  1. import os.path
  2. from django.shortcuts import render,HttpResponse,redirect
  3. from django.views import View
  4. from django.conf import settings
  5. # Create your views here.
  6. class index(View):
  7. html = 'h5_upload_file.html'
  8. def get(self,request):
  9. # print(request.GET) # <QueryDict: {}> GET请求数据
  10. return render(request,self.html)
  11. def post(self,request):
  12. user = request.POST.get('user')
  13. file_obj = request.FILES.get('head-png') # 获取文件
  14. file_name = os.path.join(settings.BASE_DIR,'img',file_obj.name) # project/img/filename
  15. with open(file_name,'wb') as f: #不能一下写进去,占用的内容太多,要一点一点写
  16. for i in file_obj:
  17. f.write(i) # 每次读取的data不是固定长度的,和读取其他文件一样,每次读一行,识别符为\r \n \r\n,遇到这几个符号就算是读了一行
  18. return HttpResponse('ok')

image.png