擅长:python、mysql、java
<p>如果您有一个字节流,希望将其保存到FileField/ImageField中,下面的一些代码可能会有所帮助:</p>
<pre><code>>>> from django.core.files.uploadedfile import InMemoryUploadedFile
>>> from cStringIO import StringIO
>>> buf = StringIO(data) # `data` is your stream of bytes
>>> buf.seek(0, 2) # Seek to the end of the stream, so we can get its length with `buf.tell()`
>>> file = InMemoryUploadedFile(buf, "image", "some_filename.png", None, buf.tell(), None)
>>> photo.image.save(file.name, file) # `photo` is an instance of `MyModel`
>>> photo.image
<ImageFieldFile: ...>
</code></pre>
<p>一些注释:</p>
<ul>
<li>你可以为图像编出你想要的任何名字,但是你可能想保持扩展名的准确性</li>
<li><code>InMemoryUploadedFile</code>的第二个参数是模型中字段的名称,因此是“image”</li>
</ul>
<p>这有点费尼基,但能完成任务。希望API在1.3/4中得到更多的清理。</p>
<p><strong>编辑:</strong><br/>
有关更简单的方法,请参见<a href="https://stackoverflow.com/questions/3330677/a-stringio-like-class-that-extends-django-core-files-file/3332232#3332232">Jason's answer</a>,不过您仍然需要知道图像的文件名。</p>