Django框架 from django.core.files.uploadedfile import InMemoryUploadedFile

作者:朱涛
链接:https://www.zhihu.com/question/23332111/answer/24239612
来源:知乎
著作权归作者所有,转载请联系作者获得授权。

model中一般会声明为FileField或者ImageField(如果是图片),使用multipart的form进行上传,上传后uploaded_file = request.FILES["file_name"]中会保存相应的文件数据,其中uploaded_file是InMemoryUploadedFile类型(

from django.core.files.uploadedfile import InMemoryUploadedFile),对于uploaded_file可以进行额外的处理(如使用PIL进行resize,保存为thumbnail等),而InMemoryUploadedFile可以直接赋值给FileField/ImageField,model save时相应的路径就可以与model中声明的关联起来。

 

我之前写的一个将上传的image进行处理生成thumbnail,并且返回InMemoryUploadedFile的函数可以参考:

 

def get_thumbnail(orig, width=200, height=200):
    """get the thumbnail of orig
    @return: InMemoryUploadedFile which can be assigned to ImageField
    """
    quality = "keep"
    file_suffix = orig.name.split(".")[-1]
    filename = orig.name
    if file_suffix not in ["jpg", "jpeg"]:
        filename = "%s.jpg" % orig.name[:-(len(file_suffix)+1)]
        quality = 95
    im = Image.open(orig)
    size = (width, height)
    thumb = im
    thumb.thumbnail(size, Image.ANTIALIAS)
    thumb_io = StringIO.StringIO()
    thumb.save(thumb_io, format="JPEG", quality=quality)
    thumb_file = InMemoryUploadedFile(thumb_io, None, filename, 'image/jpeg',
                                      thumb_io.len, None)
    return thumb_file

 

使用时:

orig_image = request.FILES.get("photo")
thumbnail = get_thumbnail(orig_image)
user.photo = orig_image
user.thumbnail = thumbnail
user.save()

转载于:https://my.oschina.net/u/2603728/blog/784872

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值