Simply save file to folder in Django

前端 未结 4 394
野趣味
野趣味 2020-12-15 17:33

I have a piece of code which gets a file from a form via POST.

file = request.FILES[\'f\']

What would be the simplest way of saving this fi

4条回答
  •  春和景丽
    2020-12-15 18:17

    Using default_storage is better than FileSystemStorage.

    You can save file to MEDIA_ROOT with FileSystemStorage but when you change DEFAULT_FILE_STORAGE backend in the future this may not work anymore.

    If you use default_storage, in the future if you want to use aws, azure etc as file store with multiple Django worker your code will work without any change.

    default_storage usage example:

    from django.core.files.storage import default_storage
    
    #  Saving POST'ed file to storage
    file = request.FILES['myfile']
    file_name = default_storage.save(file.name, file)
    
    #  Reading file from storage
    file = default_storage.open(file_name)
    file_url = default_storage.url(file_name)
    

提交回复
热议问题