How to copy InMemoryUploadedFile object to disk

后端 未结 5 644
别那么骄傲
别那么骄傲 2020-11-29 02:09

I am trying to catch a file sent with form and perform some operations on it before it will be saved. So I need to create a copy of this file in temp directory, but I don\'t

5条回答
  •  青春惊慌失措
    2020-11-29 02:45

    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_storage
    
    filename = "whatever.xyz" # received file name
    file_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.

提交回复
热议问题