0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Web画面からS3のファイルを直接ダウンロードする

Posted at

Lambda関数で生成するプリサインドURLを利用してS3のファイルをダウンロードする処理の作成手順です。

image

手順の流れ

  • ダウンロードURLを作成する AWS Lambda 関数 を作成します。
  • 生成したURLを画面へ出力します。

ダウンロードURLを作成する AWS Lambda 関数 を作成します

👇これより先は下記記事の内容を前提とします
Web画面からS3へ直接ファイルアップロードする

  • generate_presigned_urlでダウンロードURLを生成します。
import json
import boto3
import traceback
import os

from botocore.client import Config

def main_logic(prefix):
    ret = []
    client = boto3.client('s3', region_name="ap-northeast-1", config=Config(signature_version='s3v4'))
    bucket_name = "your.bucket.name.xxxxxxxxxxxx"
    response = client.list_objects_v2(Bucket=bucket_name, Prefix=prefix)
    if 'Contents' in response:
      contents = response['Contents']
      for content in contents:
        if content['Size'] > 0:
            finfo = {}
            finfo['name'] = content['Key'].split('/')[-1]
            finfo['size'] = int(content['Size'] / 1024)
            download_url = client.generate_presigned_url(
                ClientMethod = "get_object",
                Params = {"Bucket" : bucket_name, "Key" : content['Key']},
                HttpMethod = "GET"
            )
            finfo['download_url'] = download_url
            ret.append(finfo)
    return ret

def lambda_handler(event, context):
    return_data = main_logic("upload_files/")
    return {
        'statusCode': 200,
        'headers': {
            'Access-Control-Allow-Origin': '*'
        },
        'body': json.dumps(return_data)
    }

生成したURLを画面へ出力します

common.service.ts

  public fileInfoList = [];
  createFileInfoList(){
    let httpHeaders = new HttpHeaders({
      'Content-Type' : 'application/json',
    });
    let options = {
      headers: httpHeaders,
    };
    let url = "https://api.xxxxxxxxxxxxxx/v1";
    this.http.get<any>(url, options).subscribe({
      next:(data) => {
        console.log("OK");
        console.log(data);
        this.fileInfoList = data;
      },
      error:(e) =>{
        console.log("NG");
        console.error(e);
      },
      complete: () => {
        console.log("complete");
      }
    })
  }

main.component.ts

  ngOnInit(): void {
    this.commonService.createFileInfoList();
  }

main.component.html

    <mat-list>
      <mat-list-item *ngFor="let info of commonService.fileInfoList">
        <mat-icon>note</mat-icon>
        &nbsp;
        {{info["name"]}}
        &nbsp;
        {{info["size"]}}
        kb
        &nbsp;
        <a href="{{info['download_url']}}" download target="_blank">
          <mat-icon>file_download</mat-icon>
        </a>
      </mat-list-item>
    </mat-list>

👇前提記事

👇関連記事

👇GitHubはこちら

👇参考URL

[keywords]
Angular S3 download

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?