Django项目 文件的上传操作


在原有的test.html中添加了上传文件的功能:





Title



{% load mysimple %}
{% old_dog "1" "张" "测试" "用例" %}

{% show_results 10 %}

#上传文件必须写enctype






在urls.py文件中写路径和函数的对应关系
urlpatterns = [
  path('upload/', views.upload),
]
在views.py文件中写 upload函数
def upload(request):
if request.method == "POST":
# 从请求的FILES中获取上传文件的文件名
filename = request.FILES["upload_file"].name
# 在项目目录下新建一个文件 二进制文件
with open(filename, "wb") as f:
# 从上传的文件对象中一点点读
for i in request.FILES["upload_file"].chunks():
# 写入本地文件
f.write(i)
return HttpResponse("上传成功")