Attribute error: 'str' object has no attribute 'read' python-django

1.7k Views Asked by At

So the scenario here is, I have a endpoint that will take a zipfile, unzip it and save it to media dir for now. Here's the whole code for that

def get_filenames(path_for_zip):
    with ZipFile(path_for_zip, 'r') as zip:
        return zip.namelist()


class Upload(View):
    def post(self, request):

        context = {}

        upload_file = request.FILES['document']
        unzip_file = get_filenames(upload_file)
        for files in unzip_file:
            print(files)
            fs = FileSystemStorage()
            fs.save('read.jpg', files)




        return render (request, 'toDo_app.html', context)

I am using FileSystemStorage as you can see. ZipFile is unzipping properly and i can see it in print(files) but the issue is at FileSystemStorage I guess, Its not getting saved and I get this error:

attribute error 'str' object has no attribute 'read'. 

Please point me out what did I do wrong and how should it be solved. Thank you.

1

There are 1 best solutions below

2
On

@zeed namelist returns the name of the files in list i.e. string in the zip. While uploading read/open the file to buffer and upload

for files in unzip_file:
    print(files)
    fs = FileSystemStorage()
    with open(files, "rb") as outstream:
        fs.save('read.jpg', outstream)