Saturday 27 July 2013

Save file from memory to disk in django

Get file from memory and save into temp directory of OS in django


This article basically for saving the file from memory to temporary directory in django.

Here is the sample code.


from django.core.files.storage import default_storage
from django.core.files.base import ContentFile
from django.conf import settings
def upload_excel_file(request):
    data = request.FILES['file']
    path = default_storage.save('tmp/' + str(data), ContentFile(data.read()))
    tmp_file_path = os.path.join(settings.MEDIA_ROOT, path)

Now this tmp_file_path is the path of your file which is now saved into tmp directory of OS.

2 comments:

  1. Thanks i looked so many places for this, this was such a tremendous help. Thank You!

    ReplyDelete
  2. After searching all over the internet, your example is undoubtedly the best. Thank you very much for taking the trouble to share the solution!

    ReplyDelete