django 前端传文件到后台项目目录

Html端:

<form action="/student/upload" method="POST" enctype="multipart/form-data">
{% csrf_token %}

<input name="photo" enctype="multipart/form-data" type="file" accept="image/jpeg,image/png,image/bmp" >

</form>

后台python view函数:

import os
from django.conf import settings
from django.core.files.base import ContentFile
from django.core.files.storage import default_storage

stu_photo=request.FILES.get('photo')
if stu_photo.size<20480000:#限制文件不能大于2M
     stu_photo.name=userid+".jpg"#“用户id.jpg”作为文件名
path=default_storage.save('static/user/student/photo/'+stu_photo.name,ContentFile(stu_photo.read()))#存储文件第一步,这里要设置文件在项目目录里的路径
     tmp_file=os.path.join(settings.MEDIA_ROOT,path)#存储文件第二步

else:
     print("文件过大,不要大于2M!!!")

执行后,可以看到在项目目录的对应文件夹下多了一个文件

原文地址:https://www.cnblogs.com/zealousness/p/7468096.html