2017-11-23 3 views
0

私はzipファイルをダウンロードするためのスクリプトを書いています。私はこのことをどうやって行うのかについてたくさんのことを読んでいますが、まだいくつかの問題があります。あなたがコードで見ることができるように、私はまず一時ファイルを作成し、それにデータを書き込んだ後、圧縮してダウンロードします。問題はその結果です。内部に空のファイルがあるzipアーカイブ。これはコードです:Django REST zipファイルのダウンロードreturn empty 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)を設定しようとしましたが、そのようなものは探していませんでした。私は問題がfzip.writeだと思うが、実際には他の解決策を見つけることができない。 ありがとう:)

答えて

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 
+0

io.BytesIO()を使用している理由を少し説明できますか? p.s.私はこの返事で何かを逃した(fzip.writeははっきりとは機能しない)が、とにかくこの解決策を試してみるだろう – JungleFever

+0

誤字を犯してしまった。私はこれを修正し、いくつかのコメントを追加しました。 –

+0

BtwこのようにしてOSErrorが返されます: [Errno 2] \ \ n \ n 文書など.etc .. – JungleFever

関連する問題