3

我曾经easy_thumbnails在我的应用程序中存储图像。我有一个模型名称Profile,其picture字段为 ThumbnailerImageField。在我的代码中,我使用以下代码获取图像

f = urllib.request.urlretrieve(picture_url)

现在, f[0] 是一个字符串,其中包含目录中文件的路径/tmp/。我想将此图像保存到我的图片字段中。所以,我使用了以下代码

profile.picture.save(os.path.basename(picture), File(open(f[0])))

但问题是保存的文件由于某种原因已损坏,我无法打开它。而当我在 中检查文件时/tmp/,它是一个正确的图像文件。谁能指出我在这里做错了什么?

编辑:

我的字段定义如下 picture = ThumbnailerImageField(upload_to=name, max_length=3072)

name如下_

def name(inst, fname):
f = sha256((fname + str(timezone.now())).encode('utf-8')).hexdigest()
f += fname
return '/'.join([inst.__class__.__name__, f])
4

1 回答 1

3
from django.core.files.temp import NamedTemporaryFile
try:
    img_temp = NamedTemporaryFile(delete=True)
    img_temp.write(
        urllib2.urlopen(picture_url).read()
    )
    img_temp.flush()
    profile.picture.save('picture.jpg', File(img_temp))
    profile.save()
except:
    pass
于 2015-12-21T09:22:13.660 回答