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

Issue

This Content is from Stack Overflow. Question asked by Jeffrey Hao

(1) Upload a tar file.

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

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))



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.


This Question was asked in StackOverflow by Jeffrey Hao and Answered by Pouya Esmaeili It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?