<p>我能弄明白。您只需将修改后的文件另存为<code>StringIO</code>,然后从中创建一个新的<code>InMemoryUploadedFile</code>。以下是完整的解决方案:</p>
<pre><code>def save(self):
import Image as pil
import StringIO, time, os.path
from django.core.files.uploadedfile import InMemoryUploadedFile
# if avatar is uploaded, we need to scale it
if self.files['avatar']:
# opening file as PIL instance
img = pil.open(self.files['avatar'])
# modifying it
img.thumbnail((150, 150), pil.ANTIALIAS)
# saving it to memory
thumb_io = StringIO.StringIO()
img.save(thumb_io, self.files['avatar'].content_type.split('/')[-1].upper())
# generating name for the new file
new_file_name = str(self.instance.id) +'_avatar_' +\
str(int(time.time())) + \
os.path.splitext(self.instance.avatar.name)[1]
# creating new InMemoryUploadedFile() based on the modified file
file = InMemoryUploadedFile(thumb_io,
u"avatar", # important to specify field name here
new_file_name,
self.files['avatar'].content_type,
thumb_io.len,
None)
# and finally, replacing original InMemoryUploadedFile() with modified one
self.instance.avatar = file
# now, when form will be saved, it will use the modified file, instead of the original
super(UserForm, self).save()
</code></pre>