Creating zip file from byte
Solution 1
ZipFile.write(filename, [arcname[, compress_type]])
takes the name of a local file to be added to the zip file. To write data from a bytearray
or bytes
object you need to use the ZipFile.writestr(zinfo_or_arcname, bytes[, compress_type])
method instead:
with zipfile.ZipFile(zipPath, 'w'):
zipFile.write('name_of_file_in_archive', zipContents)
Note: if request.POST.get("zipFile")
already is bytes
(or str
in python2) you don't need to convert it to a bytearray
before writing it to the archive.
Solution 2
JSZip already made a zip archive. The zipfile module is for accessing zip file contents, but you don't need to parse it to store it. In addition, bytearray can be created directly from strings so the map(ord,) is superfluous, and write can handle strings as well (bytearray is for handling numeric binary data or making a mutable stringlike object). So a slightly simplified variant might be:
zipContents = request.POST.get("zipFile")
zipPath = 'uploadFile' + str(uuid.uuid4()) + '.zip'
with open(zipPath, 'wb') as zipFile:
zipFile.write(zipContents)
Tahreem Iqbal
Updated on June 27, 2022Comments
-
Tahreem Iqbal almost 2 years
I'm sending byte string of a zip file from client side using
JSZip
and need to convert it back to zip on server side. the code I've tried isn't working.b = bytearray() b.extend(map(ord, request.POST.get("zipFile"))) zipPath = 'uploadFile' + str(uuid.uuid4()) + '.zip' myzip = zipfile.ZipFile(zipPath, 'w') with myzip: myzip.write(b)
It gives the error:
stat: path too long for Windows
How do I save my byte string as a zip file?
-
Tahreem Iqbal over 7 yearswith a slight modification (` zipFile.write(bytes(zipContents, 'UTF-8')) `) it created the zip file but opening it gives error that the file is damaged.
-
Tahreem Iqbal over 7 yearsI give up. I'll just compress the file from client side instead. Thanks.
-
Yann Vernier over 7 yearsWhat? I thought you already did, why else would you mention JSZip? Also, zip files aren't text and shouldn't use character encodings like UTF-8. They're binary data. Your
request
object might be important because of that; it likely has to decode the data from base64, urlescape or similar.