pythondjangodjango-rest-frameworkfile-uploaddjango-file-upload

How to get the file object in `request.data` in Django?


  1. Upload a tar file.

  2. How to get the file object in request.data?

class AlbumViewSet(viewsets.ModelViewSet):

    @action(methods=['POST'], detail=False, url_path='upload-album')
    def upload_album(self, request):
        # Upload one tar file.
        logging.error("----> request.data = {}".format(request.data))

Thanks


Solution

  • You can get file object in request.FILES.
    request.FILES is dictionary like object containing all uploaded files. You can access your file object by its name, like this: request.FILES['my-file-name']

    For example, if you want to log filename::

    class AlbumViewSet(viewsets.ModelViewSet):
    
        @action(methods=['POST'], detail=False, url_path='upload-album')
        def upload_album(self, request):
            # Upload one tar file.
            logging.error("----> Uploaded file name = {}".format(request.FILES['my-file-name'].name))
    

    Check here for more details.