1

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...?

Simon Steinberger
  • 6,605
  • 5
  • 55
  • 97

1 Answers1

2

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

JPG
  • 82,442
  • 19
  • 127
  • 206
  • Thank you, worked for me! May be good to know: `FileSystemStorage` returns the actual name of the stored file. Because if a file with the original name already exists, Django will append some characters to the new filename to avoid the collision. – Simon Steinberger Nov 03 '22 at 17:57