5
3

More than 1 year has passed since last update.

S3内のZIPファイルをAPI経由でダウンロードする方法

Last updated at Posted at 2021-09-04

はじめに

ZIPファイルをAPI経由でダウンロードする方法について、意外とやり方が分からず手こずったため、メモとして残しておく。

事前準備

・S3にバケットを作成し、直下に任意のZIPファイルを格納しておく。
・ローカルPCにPython3系のインストール(ダウンロードファイルをデコードするために使用)

流れ

1.ダウンロード用のAPIの準備
  1-1).Lambdaの作成
  1-2).API Gatewayの作成

2.ダウンロード後の変換

1.ダウンロード用のAPIの準備

1-1).Lambdaの作成(Node.js 14.x)

index.js
var AWS = require('aws-sdk')
var s3 = new AWS.S3()

exports.handler = async (event) => {


    var params = {
        Bucket: "バケット名", 
        Key: "ZIPファイル名"
    };

    const zip_data = await s3.getObject(params).promise()

    const response = {
        statusCode: 200,
        "headers": {
            "Content-Disposition": 'attachment; filename="download_filename.zip"',
            "Content-Type": 'application/zip'
        },
        // base64でテキストに変換している。
        body: zip_data.Body.toString('base64')
    }

    return response;
}

1-2).API Gatewayの作成

・REST APIを構築
・GETメソッドの "統合リクエスト"内の『Lambda プロキシ統合の使用』のチェックを付ける。
 ※このチェックを忘れると、URLを叩いた際returnの中身がそのままJSON形式で表示されてしまい、ファイルダウンロードが走らない。
Qiita-no054_img01.jpg

このAPIから上記Lambdaを実行できる様にしたら、APIをデプロイしてURLを叩いてダウンロードできるか確認。(その他、特別な設定は不要。)

2.ダウンロード後の変換

1の手順によりAPI経由で(URLを叩くと)ZIPファイルがダウンロードできる様になったが、中身は元のZIPファイルの状態ではないため展開ができない。

そこで、以下の様にデコードして元の形に戻す必要がある。(Pythonで記載)

import base64

# ダウンロードしたZIPファイル
from_file_path = '【ダウンロードファイルが置いてあるパス】/download_filename.zip'

# base64でデコードして元の状態に戻したZIPファイル(作成場所)
to_file_path = '【出力したい場所のパス】/zip_decode_filename.zip'

with open(from_file_path, 'r') as f_file:
    data = f_file.read()
    print(data)

decoded_zip = base64.b64decode(data.encode())

with open(to_file_path, 'bw') as t_file:
    t_file.write(decoded_zip)

上記を実行して作成されたZIPファイルは、展開もできて中身も元の状態となっている。

5
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3