文件上传处理
-
-
FILES中的每个键为
<input type="file" name="" />
中的name -
注意:FILES只有在请求的方法为POST 且提交的
<form>
带有enctype="multipart/form-data" 的情况下才会包含数据。否则,FILES 将为一个空的类似于字典的对象 -
from django.db import models # Create your models here. class User(models.Model): name = models.CharField(max_length=50, verbose_name="姓名") avatar = models.ImageField(max_length=250, upload_to=‘avatar/%Y/%m/%d/‘) attachment = models.FileField(max_length=250, upload_to=‘atta/%Y/%m/%d/‘) class Meta: db_table = "home_user" verbose_name = "用户信息" verbose_name_plural = verbose_name
注意:如果属性类型为ImageField需要安装PIL包
pip install Pillow # 把上面User模型进行数据迁移 # python manage.py makemigrations # python manage.py migrate
-
在项目根目录下创建保存上传文件的根文件夹
-
图片上传后,会被保存到上面配置的根文件夹下
-
# 设置上传文件的保存根目录[此处指定的目录必须手动创建] MEDIA_ROOT = BASE_DIR / "uploads"
<html> <head> <title>文件上传</title> </head> <body> <form method="post" action="/home/avatar" enctype="multipart/form-data"> <input type="text" name="name"><br> <input type="file" name="avatar"><br> <input type="file" name="atta"/><br> <input type="submit" value="上传"> </form> </body> </html>
手动上传的视图代码
from django.conf import settings def upload(request): if request.method == "POST": avatar = request.FILES[‘avatar‘] fname = ‘%s/avatar/%s‘ % (settings.MEDIA_ROOT,avatar.name) with open(fname, ‘w‘) as pic: for c in avatar.chunks(): pic.write(c) return HttpResponse("ok") else: return HttpResponse("error")
模型中调用ImageField或FileField进行处理
from django.views import View from django.http.response import HttpResponse from .models import User class UserView(View): def get(self,request): print( request.FILES ) # 获取上传文件列表 print( request.FILES.get("avatar") ) return HttpResponse("上传文件") def post1(self,request): """request.FILES只会在post请求中接受上传文件,客户端中必须设置enctype=multipart/form-data""" print( request.FILES ) # 获取上传文件列表 print( request.FILES.get("avatar") ) print( request.FILES.get("avatar").content_type ) # 上传文件的MIME类型 if "image" in request.FILES.get("avatar").content_type: # 判断文件类型 if request.FILES.get("avatar").content_type.split("/")[-1] in ["png","jpg","jpeg","gif"]: # 图片类型 print("处理上传文件!") print( request.FILES.get("avatar").size ) # 上传文件的大小 print( type(request.FILES.get("avatar")) ) return HttpResponse("上传文件") def post(self,request): user = User.objects.create( name=request.POST.get("name"), avatar=request.FILES.get("avatar"), attachment=request.FILES.get("atta") ) return HttpResponse("上传文件处理完成!")
最后的结果: