做者:朱濤
連接: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()