Tahreem Iqbal
Tahreem Iqbal

Reputation: 1015

Creating zip file from byte

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?

Upvotes: 3

Views: 22956

Answers (2)

mata
mata

Reputation: 69042

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 shown below:

with zipfile.ZipFile(zipPath, 'w'):
    zipFile.writestr('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.

Upvotes: 11

Yann Vernier
Yann Vernier

Reputation: 15877

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)

Upvotes: 4

Related Questions