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!!!")

 

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

 

相关文章:

  • 2021-08-03
  • 2021-12-22
  • 2022-12-23
  • 2021-08-23
  • 2022-12-23
  • 2021-11-02
  • 2022-02-05
猜你喜欢
  • 2022-02-07
  • 2021-11-17
  • 2022-03-10
  • 2021-09-29
  • 2021-04-09
  • 2022-02-08
  • 2021-12-01
相关资源
相似解决方案