Search code examples
djangofileuploadstorage

Save uploaded InMemoryUploadedFile as tempfile to disk in Django


I'm saving a POST uploaded file to disk by using a technique described here: How to copy InMemoryUploadedFile object to disk

from django.core.files.storage import default_storage
from django.core.files.base import ContentFile
from django.conf import settings

data = request.FILES['image']
path = default_storage.save('tmp/%s' % filename, ContentFile(data.read()))
tmp_file = os.path.join(settings.MEDIA_ROOT, path)

The file does get uploaded and stored at the specified location. However, the content is garbled. It's an image - and when I look at the stored file, I see, the characters are not the same and the image file is damaged. The filesize, however, is the same as the original.

I guess, I need to do some conversion before saving the file, but how/which...?


Solution

  • Highly recommend using the FileSystemStorage directly instead of default_storage as the DEFAULT_FILE_STORAGE can be set to another value.

    from django.core.files.storage import FileSystemStorage
    from django.http import HttpResponse
    
    
    def simple_view(request):
        in_memory_file_obj = request.FILES["file"]
        FileSystemStorage(location="/tmp").save(in_memory_file_obj.name, in_memory_file_obj)
        return HttpResponse("Success")
    

    Note: Solution tested with Django 4.1