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类型(django

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

 

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

 

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

 

使用时:orm

orig_image = request.FILES.get("photo")
thumbnail = get_thumbnail(orig_image)
user.photo = orig_image
user.thumbnail = thumbnail
user.save()
相关文章
相关标签/搜索