urls.py文件:
1 urlpatterns = [ 2 path('admin/', admin.site.urls), 3 4 path('login/', views.login), 5 path('index/', views.index), 6 path('logout/', views.logout), 7 path('reg/', views.register), 8 path('upload/',views.upload) #文件上传
views.py文件:
1 from django.views.decorators.csrf import csrf_exempt #先导入以后下方调用csrf_exempt 2 3 #文件上传示例 4 @csrf_exempt #加上这个装饰器 下面这个视图就不校验csrf 5 def upload(request): 6 if request.method == "POST": 7 file_obj = request.FILES.get("file") #使用FILES.get 获取文件对象 8 with open(file_obj.name,"wb") as f: # 上传的文件将会展示在根目录下面 9 for line in file_obj: 10 f.write(line) 11 return render(request,"upload.html")
upload.html 页面:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>文件上传功能</title> 6 <meta name="viewport" content="width=device-width, initial-scale=1"> 7 </head> 8 <body> 9 {#上传文件 type为file时,enctype一定要选择#} 10 <form action="/upload/" method="post" enctype="multipart/form-data"> 11 {# 每个p标签都要记得写name#} 12 {# {% csrf_token %} 在views调用csrf_exempt 可以不用写这个#} 13 <p>文件上传:<input type="file" name="file"></p> 14 <p><input type="submit" value="上传"></p> 15 </form> 16 </body> 17 </html>
settings.py文件:
标签:文件,file,views,--,示例,django,csrf,path,上传 From: https://www.cnblogs.com/zs0621/p/16727884.html