How to copy InMemoryUploadedFile object to disk How to copy InMemoryUploadedFile object to disk python python

How to copy InMemoryUploadedFile object to disk


This is similar question, it might help.

import osfrom django.core.files.storage import default_storagefrom django.core.files.base import ContentFilefrom django.conf import settingsdata = request.FILES['image'] # or self.files['image'] in your formpath = default_storage.save('tmp/somename.mp3', ContentFile(data.read()))tmp_file = os.path.join(settings.MEDIA_ROOT, path)


As mentioned by @SÅ‚awomir Lenart, when uploading large files, you don't want to clog up system memory with a data.read().

From Django docs :

Looping over UploadedFile.chunks() instead of using read() ensures that large files don't overwhelm your system's memory

from django.core.files.storage import default_storagefilename = "whatever.xyz" # received file namefile_obj = request.data['file']with default_storage.open('tmp/'+filename, 'wb+') as destination:    for chunk in file_obj.chunks():        destination.write(chunk)

This will save the file at MEDIA_ROOT/tmp/ as your default_storage will unless told otherwise.


Here is another way to do it with python's mkstemp:

### get the inmemory filedata = request.FILES.get('file') # get the file from the curl### write the data to a temp filetup = tempfile.mkstemp() # make a tmp filef = os.fdopen(tup[0], 'w') # open the tmp file for writingf.write(data.read()) # write the tmp filef.close()### return the path of the filefilepath = tup[1] # get the filepathreturn filepath