django 前端傳文件到後臺項目目錄
阿新 • • 發佈:2017-09-03
函數 enc default nbsp cor font imp for multi ContentFile
from django.core.files.storage import default_storage
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
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!!!")
執行後,可以看到在項目目錄的對應文件夾下多了一個文件
django 前端傳文件到後臺項目目錄