2017-04-13 86 views
0

ここは私が使ったリンクです(Download files from Amazon S3 with Django)。これを使用して私は1つのファイルをダウンロードすることができます。S3から複数のファイルをダウンロードするdjango

コード:

s3_template_path = queryset.values('file') 
filename = 'test.pdf' 
conn = boto.connect_s3('<aws access key>', '<aws secret key>') 
bucket = conn.get_bucket('your_bucket') 
s3_file_path = bucket.get_key(s3_template_path) 
response_headers = { 
'response-content-type': 'application/force-download', 
'response-content-disposition':'attachment;filename="%s"'% filename 
} 
url = s3_file_path.generate_url(60, 'GET', 
      response_headers=response_headers, 
      force_http=True) 
return HttpResponseRedirect(url) 

私はジッパーが良いだろうと、S3から複数のファイルをダウンロードする必要があります。上記の方法を変更して使用することはできますか?そうでない場合は、他の方法をお勧めします。

+0

は、あなたが探しているファイルごとに同じs3_template_pathであれば、これを変更する場合は必ず? – kujosHeist

+0

いいえ、テンプレートのパスは異なります – Manasa

答えて

1

これは可能な解決策です。基本的には、各ファイルをダウンロードしてフォルダに入れてから、ユーザーに返します。

ないs3_template_pathは、各ファイルの同じですが、neccessary

# python 3 

import requests 
import os 
import zipfile 

file_names = ['test.pdf', 'test2.pdf', 'test3.pdf'] 

# set up zip folder 
zip_subdir = "download_folder" 
zip_filename = zip_subdir + ".zip" 
byte_stream = io.BytesIO() 
zf = zipfile.ZipFile(byte_stream, "w") 


for filename in file_names: 
    s3_template_path = queryset.values('file') 
    conn = boto.connect_s3('<aws access key>', '<aws secret key>') 
    bucket = conn.get_bucket('your_bucket') 
    s3_file_path = bucket.get_key(s3_template_path) 
    response_headers = { 
    'response-content-type': 'application/force-download', 
    'response-content-disposition':'attachment;filename="%s"'% filename 
    } 
    url = s3_file_path.generate_url(60, 'GET', 
       response_headers=response_headers, 
       force_http=True) 

    # download the file 
    file_response = requests.get(url) 

    if file_response.status_code == 200: 

     # create a copy of the file 
     f1 = open(filename , 'wb') 
     f1.write(file_response.content) 
     f1.close() 

     # write the file to the zip folder 
     fdir, fname = os.path.split(filename) 
     zip_path = os.path.join(zip_subdir, fname) 
     zf.write(filename, zip_path)  

    # close the zip folder and return 
    zf.close() 
    response = HttpResponse(byte_stream.getvalue(), content_type="application/x-zip-compressed") 
    response['Content-Disposition'] = 'attachment; filename=%s' % zip_filename 
    return response   
+0

申し訳ありませんが、file_response = requests.get(url)がファイルを正しく返す限り、このバージョンは正常に動作します。 – kujosHeist

+0

ありがとう、これを試してみてください – Manasa

+0

さて、s3_template_path内部ループ、それが動作するかどうかを教えてください – kujosHeist

関連する問題