通过 Django 下载 Zip 文件,文件解压为 cpzg

Downloading Zip file through Django, file decompresses as cpzg

我的目标是将一系列字符串解析为一系列文本文件,这些文本文件被压缩为 Zip 文件,并由 Web 应用程序使用 Django 的 HTTP 响应下载。

在 PyCharm 中进行本地开发,我的方法输出一个名为“123.zip”的 Zip 文件,其中包含 6 个名为“123_1”、“123_2 等”的单独文件.包含我的短语中的字母没有问题。

问题是当我将代码推送到我的网络应用程序并包含文件将下载的 Django HTTP 响应时,但当我去提取它时它会生成“123.zip.cpzg”。提取它又给我 123.zip(1) 一个令人沮丧的无限循环。我哪里出错了有什么建议吗?

在本地运行以生成“123.zip”的代码:

def create_text_files1():
    JobNumber = "123"
    z = zipfile.ZipFile(JobNumber +".zip", mode ="w")
    phrase = "A, B, C, D, EF, G"
    words = phrase.split(",")
    x =0

    for word in words:
        word.encode(encoding="UTF-8")
        x = x + 1
        z.writestr(JobNumber +"_" + str(x) + ".txt", word)
    z.close()

我的网络应用程序中方法的其他部分:

    response = HTTPResponse(z, content_type ='application/zip')
    response['Content-Disposition'] = "attachment; filename='" + str(jobNumber) + "_AHTextFiles.zip'"

仔细看看example provided in this answer

注意一个 StringIO 被打开,zipFile 以 StringIO 作为 "File-Like Object" 被调用,然后,至关重要的是,在 zipFile 关闭后,StringIO 在 HTTPResponse 中被返回。

# Open StringIO to grab in-memory ZIP contents
s = StringIO.StringIO()

# The zip compressor
zf = zipfile.ZipFile(s, "w")

# Grab ZIP file from in-memory, make response with correct MIME-type
resp = HttpResponse(s.getvalue(), mimetype = "application/x-zip-co mpressed")

我会根据你的情况推荐一些东西。

  1. 使用 BytesIO 实现向前兼容性
  2. 利用 ZipFile 的内置上下文管理器
  3. 在你的 Content-Disposition 中,注意 "jobNumber" 与 "JobNumber"

尝试这样的事情:

def print_nozzle_txt(request):
    JobNumber = "123"
    phrase = "A, B, C, D, EF, G"
    words = phrase.split(",")
    x =0

    byteStream = io.BytesIO()

    with zipfile.ZipFile(byteStream, mode='w', compression=zipfile.ZIP_DEFLATED,) as zf:
        for word in words:
            word.encode(encoding="UTF-8")
            x = x + 1
            zf.writestr(JobNumber + "_" + str(x) + ".txt", word)

    response = HttpResponse(byteStream.getvalue(), content_type='application/x-zip-compressed')
    response['Content-Disposition'] = "attachment; filename='" + str(JobNumber) + "_AHTextFiles.zip'"
    return response