Django InMemoryUploadedFile


i want to compress images and by myself i couldn’t do it.i found this solution, that works.the thing I don’t understand are, where the file is saved, and the file after the process is finish, automatically deleted or remains somewhere,I would be grateful if anyone can explain to me how InMemoryUploadedFile works

class Image(models.Model):
owner= models.ForeignKey(settings.AUTH_USER_MODEL)
title = models.CharField(max_length=255)

image = models.ImageField(upload_to=get_uplaod_file_name)

def save(self):
    im =

    output = BytesIO()

    im = im.resize((100, 100)), format='JPEG', quality=90)

    self.image = InMemoryUploadedFile(output, 'ImageField', "%s.jpg" %'.')[0], 'image/jpeg',
                                    sys.getsizeof(output), None)

    super(Image, self).save()

You can read the source for both InMemoryUploadedFile (django.core.files.uploadedfile) and MemoryFileUploadHandler (django.core.files.uploadhandler) to see how they work. You can also compare them to TemporaryUploadedFile and TemporaryFileUploadHandler (same files) to see how they’re different.

From the docs for InMemoryUploadedFile:

A file uploaded into memory (i.e. stream-to-memory) …

And for MemoryFileUploadHandler:

File upload handler to stream uploads into memory (used for small files).

You might also want to review Managing Files for more information about handling uploaded files.

Thank you very much Ken