django上传图片

    images = models.ImageField('图片', upload_to='cicles/%Y/%m/%d', 	storage=ImageStorage(), null=True, blank=True)

# 给上传的图片重命名
from django.core.files.storage import FileSystemStorage


class ImageStorage(FileSystemStorage):
    from django.conf import settings

    def __init__(self, location=settings.MEDIA_ROOT, base_url=settings.MEDIA_URL):
        # 初始化
        super(ImageStorage, self).__init__(location, base_url)

    # 重写 _save方法
    def _save(self, name, content):
        # name为上传文件名称
        import os, time, random
        # 文件扩展名
        ext = os.path.splitext(name)[1]
        # 文件目录
        d = os.path.dirname(name)
        # 定义文件名,年月日时分秒随机数
        fn = time.strftime('%Y%m%d%H%M%S')
        fn = fn + '_%d' % random.randint(0, 100)
        # 重写合成文件名
        name = os.path.join(d, fn + ext)
        # 调用父类方法
        return super(ImageStorage, self)._save(name, content)

接口请求接口

def save_userimg(request, img):
    # 获取上传图片的名称
    img_name = img.name
    # 获取后缀
    ext = os.path.splitext(img_name)[1]
    print(img_name, ext)
    # 重新规定图片名称,图片类型
    fn = time.strftime('%Y%m%d%H%M%S')
    fn = fn + '_%d' % random.randint(0, 100)
    img_path = 'cicles'
    times = datetime.datetime.now()
    year = times.strftime('%Y')
    month = times.strftime('%m')
    day = times.strftime('%d')
    img_path = os.path.join(img_path, year, month, day)
    print("img_path:", img_path)
    if not os.path.exists(os.path.join(settings.MEDIA_ROOT, img_path)):
        os.makedirs(os.path.join(settings.MEDIA_ROOT, img_path))
        print("新创建了文件夹")
    filepath = os.path.join(settings.MEDIA_ROOT, img_path, fn + ext)
    print("filepath:", filepath)
    with open(filepath, 'wb') as fp:
        for info in img.chunks():
            fp.write(info)  # chunks是以文件流的方式来接受文件,分段写入
    img_url = "http://" + request.get_host() + "/media/" + img_path +fn + ext
    # return img_url, filepath
    return img_path + fn + ext

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值