Reputation: 23
I'm trying to upload a zip file to my server using python flask request and then unzip it using zipfile module.
Here is my code:
@app.route('/uoload', methods=['POST']) def upload (): data = request.data current_path = os.getcwd() filename = "file.zip" with open(os.path.join(upload_path, filename), 'w') as file: file.write(data) try: with zipfile.ZipFile(os.path.join(current_path + filename)) as zf: zf.extractall(os.path.join(upload_path)) except BadZipfile as e: print e return "", 406
But it seems like the uploaded file is damaged somehow. Because when i'm trying to unzip it, BadzipFile exception occurs and it says : "Bad magic number for file header" .
Upvotes: 2
Views: 5397
Reputation: 719
The problem seems to be that you are using open
to create a zip archive.
When you use open
, python will create write the data to the file and will name it like you wanted. That doesn't make it a zip archive. That is why it fails to extract data from the file.
If you want to create a zip archive use:
import zipfile
zf = zipfile.ZipFile('file.zip', mode='w')
zf.write('add_this_file_to_zip_archive.txt')
zf.close()
Upvotes: 0