Django REST zip文件下载返回空拉链

时间:2017-11-23 09:34:39

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

我正在编写一个脚本来下载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)或者搜索(0)和类似的东西。我认为问题是fzip.write,但实际上我无法想出其他解决方案,任何人都可以帮忙吗? 谢谢:))

1 个答案:

答案 0 :(得分:0)

# 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