Search code examples
pythonflaskzip

zipfile.BadZipFile: Bad offset for central directory


I have designed a webpage that allows the user to upload a zip file. What I want to do is store this zip file directly into my sqlite database as a large binary object, then be able to read this binary object as a zipfile using the zipfile package. Unfortunately this doesn't work because attempting to pass the file as a binary string in io.BytesIO into zipfile.ZipFile gives the error detailed in the title.

For my MWE, I exclude the database to better demonstrate my issue.

views = Blueprint('views', __name__)
@views.route("/upload", methods=["GET", "SET"])
def upload():
    # Assume that file in request is a zip file (checked already)
    f = request.files['file']
    zip_content = f.read()
    # Store in database
    # ...
    # at some point retrieve the file from database
    archive = zipfile.ZipFile(io.BytesIO(zip_content))

    return ""

I have searched for days on-end how to fix this issue without success. I have even printed out zip_content and the contents of io.BytesIO(zip_content) after applying .read() and they are exactly the same string.

What am I doing wrong?


Solution

  • Solved. Using f.read() only gets the name of the zip file. I needed to use f.getvalue() instead to get the full file contents.