Daniel Thompson
Daniel Thompson

Reputation: 2351

Python3 Django ZipFile HttpResponse UnicodeDecodeError

I created a zip file like so:

        zipped_file = zipfile.ZipFile("csvOutput{}.zip".format(timestamp), 'w')
        zipped_file.write(sms_file_path)
        zipped_file.write(mail_maga_file_path)
        zipped_file.close()

And want to send it, which I am currently using this code:

        response_file = open('csvOutput{}.zip'.format(timestamp))
        response = HttpResponse(response_file, content_type="application/force-download")
        response['Content-Disposition'] = 'attachment; filename=csvOutput{}.zip"'.format(timestamp)
        return response
        raise Http404

But maybe something I am using is out of date? Python keeps crashing with a byte it can't decode in unicode:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x94 in position 14: invalid start byte

Says line 100 is throwing the error, which would be the line with HttpResponse()

Edit: I've changed the content_type to application/zip and am getting a new error (that seems better?):

caution:  zipfile comment truncated
error [output.zip]:  missing 3232109644 bytes in zipfile
  (attempting to process anyway)
error [output.zip]:  attempt to seek before beginning of zipfile
  (please check that you have transferred or created the zipfile in the
  appropriate BINARY mode and that you have compiled UnZip properly)

Upvotes: 0

Views: 643

Answers (2)

user2111922
user2111922

Reputation: 1129

I've managed to fix the issue, by opening the file with 'rb' as in:

response_file = open('csvOutput{}.zip'.format(timestamp), 'rb')

Upvotes: 1

Rakesh
Rakesh

Reputation: 82795

Looks like this issue is with your time stamp string.

response_file = open('csvOutput{}.zip'.format(str(timestamp).encode('utf-8').strip()))

or

response_file = open('csvOutput{}.zip'.format(str(timestamp).encode('ISO-8859-1').strip()))

Upvotes: 1

Related Questions