Python3 Django ZipFile HttpResponse UnicodeDecodeError

时间:2018-01-15 09:51:16

标签: python django

我创建了一个像这样的zip文件:

        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()

想要发送它,我目前正在使用此代码:

        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

但是我使用的东西可能已经过时了? Python不断崩溃,它无法在unicode中解码:

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

表示line 100正在抛出错误,即HttpResponse()

修改:我已将content_type更改为application/zip并收到新错误(这似乎更好?):

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)

2 个答案:

答案 0 :(得分:1)

看起来这个问题与您的时间戳字符串有关。

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

{{1}}

答案 1 :(得分:0)

我已经设法解决此问题,方法是使用“ rb”打开文件,如下所示:

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