无需写回文件系统,然后通过打开调用将文件带回内存的方法是利用StringIO和Django InMemoryUploadedFile。这是有关如何执行此 *** 作的快速示例。假设您已经有一个名为“ thumb”的缩略图:
import StringIOfrom django.core.files.uploadedfile import InMemoryUploadedFile# Create a file-like object to write thumb data (thumb data previously created# using PIL, and stored in variable 'thumb')thumb_io = StringIO.StringIO()thumb.save(thumb_io, format='JPEG')# Create a new Django file-like object to be used in models as ImageField using# InMemoryUploadedFile. If you look at the source in Django, a# SimpleUploadedFile is essentially instantiated similarly to what is shown herethumb_file = InMemoryUploadedFile(thumb_io, None, 'foo.jpg', 'image/jpeg', thumb_io.len, None)# once you have a Django file-like object, you may assign it to your ImageField# and save....
让我知道是否需要进一步说明。我现在正在我的项目中进行此工作,并使用django-storages上传到S3。这花了我大部分时间在这里正确地找到解决方案。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)