Sometimes, we want to copy InMemoryUploadedFile object to disk with Python Django.
In this article, we’ll look at how to copy InMemoryUploadedFile object to disk with Python Django.
How to copy InMemoryUploadedFile object to disk with Python Django?
To copy InMemoryUploadedFile object to disk with Python Django, we can use the save
method.
For instance, we write
import os
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/somename.mp3', ContentFile(data.read()))
tmp_file = os.path.join(settings.MEDIA_ROOT, path)
in our view function.
We get the file from request.FILES
.
And then we call default_storage.save
with the file path to save to and the ContentFile
object that we create by reading data
.
Then we get the path of the saved file with os.path.join(settings.MEDIA_ROOT, path)
.
Conclusion
To copy InMemoryUploadedFile object to disk with Python Django, we can use the save
method.