django + python上传文件的两种方式

突然心血来潮,研究了下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: #以二进制留写的方式写入文件,文件不存在则自动创建
    if file.multiple_chunks():#判断如果文件大于默认值2.5M(可以修改)则采用分块的方式上传
        for fc in file.chunks():
            of.write(fc)
    else:
        of.write(file.read())#小于2.5M则直接上传

第二:利用django自带的文件存储系统上传

1. settings.py文件设置同上

2. html模板同上

3. 模型类定义

from django.db import models

class UserInfo(models.Model):
    photo = models.ImageFile(upload_to="user_photo")#如果目录不存在django会自动创建

4. python后台代码

file = request.FILES.get('photo')

u = UserInfo()
u.photo = file

u.save()

猜你喜欢

转载自blog.csdn.net/lixiaosenlin/article/details/103053728
今日推荐