【问题标题】:Django REST zip file download return empty zipDjango REST zip 文件下载返回空 zip
【发布时间】:2017-11-23 09:34:38
【问题描述】:

我正在编写一个脚本来下载一个 zip 文件。我读了很多关于如何做到这一点的文章,但我仍然遇到了一些麻烦。正如你在代码中看到的,我首先创建了一个临时文件,在上面写入数据,然后压缩并下载。问题是结果:一个 zip 存档,里面有一个空文件。这是代码:

    f = tempfile.NamedTemporaryFile()
    f.write(html.encode('utf-8')) 
    print(f.read) #the "writing of tmp file" seem to work, the expected output is right

    fzip = ZipFile("test.zip","w")
    fzip.write(f.name,'exercise.html') #this file remains empty

    response = HttpResponse(fzip, content_type="application/zip")
    response['Content-Disposition'] = 'attachment; "filename=test.zip"'
    return response

我已经尝试设置 NamedTemporaryFile(delete=False) 或 seek(0) 之类的东西。我认为问题出在 fzip.write 上,但实际上我想不出其他解决方案,有人可以帮忙吗? 谢谢:)

【问题讨论】:

    标签: python django download django-rest-framework zip


    【解决方案1】:
    # Create a buffer to write the zipfile into
    zip_buffer = io.BytesIO()
    
    # Create the zipfile, giving the buffer as the target
    with zipfile.ZipFile(zip_buffer, 'w') as zip_file:
        f.seek(0)
        zip_file.write(html.encode('utf-8'),'exercise.html')
        f.close()
    
    response = HttpResponse(content_type='application/x-zip-compressed')
    response['Content-Disposition'] = 'attachment; filename=test.zip'
    # Write the value of our buffer to the response
    response.write(zip_buffer.getvalue())
    
    return response
    

    【讨论】:

    • 你能解释一下你为什么使用 io.BytesIO() 吗? p.s.您在此回复中遗漏了一些内容(显然,fzip.write 不起作用)但无论如何我都会尝试此解决方案
    • 抱歉打错了。我修复了这个问题并添加了一些评论。
    • 顺便说一句,这样响应会返回一个 OSError: [Errno 2] No such file or directory: '\n\n \n \n \n \n 文档 etc..etc..
    • 现在我正在重新阅读我的答案,但我不明白您为什么需要NamedTemporaryFile(错误的来源)。编辑了我的答案。
    • 我想通了,我没有使用 io.BytesIo(),解决方案很像我第一个问题中的代码,但现在可以了,非常感谢帮助:)
    猜你喜欢
    • 2023-02-16
    • 2012-03-14
    • 1970-01-01
    • 2015-10-18
    • 2020-10-26
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    相关资源
    最近更新 更多