I am developing a small project that aims to enable to the user to submit a zip file. The system should read the file, extract it and save its contents to the database.
I am having this error : a bytes-like object is required, not 'list' because I tried to use BytesIo. without it, the error said :" fpin.seek(0, 2) AttributeError: 'list' object has no attribute 'seek'"
My code looks like this
files = request.FILES.getlist('document[]')
with zipfile.ZipFile(io.BytesIO(files), "r")as archive:
for zippedFileName in archive.namelist():
with archive.open(zippedFileName) as myfile:
with io.BytesIO() as buf:
buf.write(myfile.read())
buf.seek(0)
file = File(buf, zippedFileName).decode('utf-8')
rbe = UploadedFile.objects.create(document=file)
rbe.user= request.user
rbe.save()
return render(request, 'uploader/index.html', {'files': files})
The error or traceback looks like this
CodePudding user response:
In Django, request.FILES.getlist
returns a list of UploadedFile
objects, each of which has a file
attribute, a file-like object that you can pass directly to the ZipFile
constructor.
Since your code apparently assumes that there is only one UploadedFile
object in the list returned by request.FILES.getlist
, you can unpack it like this:
uploaded_file, = request.FILES.getlist('document[]')
with zipfile.ZipFile(uploaded_file.file, "r") as archive:
for zippedFileName in archive.namelist():
...
# you should return after the for loop, not within it
return render(request, 'uploader/index.html', {'files': [uploaded_file]})