How to read or save a file from MultiValueDict in Django

3.3k Views Asked by At

I'm sending a excel file from Angular to Django. I want to read the file using Pandas and perform some operations in the file, but I'm not sure how to do it.

class fileupload(APIView) :
    def post(self, request): 
        f = request.FILES
        print(f)

When I print, it shows below,

<MultiValueDict: {'excelfile': [<InMemoryUploadedFile: New_Excel.xlsx (application/vnd.openxmlformats-officedocument.spreadsheetml.sheet)>]}>

Here, I want to save this file to some location and use pandas to perform operations or if possible, directly would need to read the file using pandas. I'm new to Django and Pandas so if anything is wrong, please help.. Thanks in advance

2

There are 2 best solutions below

0
On BEST ANSWER
from django.core.files.storage import default_storage    
from django.core.files.base import ContentFile
file_objs = request.data.getlist('files')
for file_obj in file_objs:
    path = default_storage.save(settings.MEDIA_ROOT, ContentFile(file_obj.read()))
    print("images path are",path)
2
On
class fileupload(APIView) :
def post(self, request): 
    f = request.data.getlist("excelfile")
    print(f) # list of elements

Now loop the f then store one by one