突然心血来潮,研究了下django+python上传文件的两种方式。
第一:直接采用文件读写的方式上传
1. settings.py文件中设置文件的存放路径和文件读取路径
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
2. html模板文件:
<form method="post" enctype="multipart/form-data">
<input type="file" name='photo'>
</form>
3. python后台代码
import os
from django.conf import settings
file = request.FILES.get('photo')
saved_path = os.path.join(settings.MEDIA_ROOT, 'user_photos')
if not os.path.exists(saved_path): #如果文件路径不存在则创建文件保存目录
os.mkdir(saved_path)
saved_file = os.path.join(saved_path, file.name)#file.name为带后缀的文件名
with open(saved_file, 'wb+') as of: #以二进制留写的方式写入文件,文件不存在则自动创建