LoginSignup
3
0

More than 3 years have passed since last update.

StrapiからGCSへファイルをアップロードする方法

Last updated at Posted at 2020-12-08

Strapi Advent Calenderの8日目は、StrapiのAPIを介して、ファイルをGoogle Cloud Storageへアップロードする方法を紹介します。

Strapi Advent Calenderのその他の記事はこちら

GCS接続準備

  1. GCPでサービスアカウントを作成(ロールはストレージ管理者)・サービスアカウントJSONをDL

  2. Strapiにstrapi-provider-upload-google-cloud-storageモジュールをインストール

$ npm i strapi-provider-upload-google-cloud-storage

3.Strapiの<project_name>/config/plugin.js に追記

module.exports = ({ env }) => ({
 upload: {
   provider: 'google-cloud-storage',
   providerOptions:{
     "serviceAccount": "サービスアカウントJSON",
     "bucketName": "<GCSのバケット名>",
     "baseUrl": "https:// storage.googleapis.com/<GCSのバケット名> "
   }
 }
});

1. ファイルのみPOSTするときの例(/upload)

ファイルだけアップロードする場合は、StrapiのUploadプラグインを使用します。

example.ts
    const body = new FormData();
    body.append('files', fileObject);
    return this.http
      .post(environment.apiUrl + '/upload', body)
      .toPromise()
      .then((res) => {
        const response: any = res;
        return response;
      })
      .catch(this.errorHandler);

2. ファイルを含んだコレクションタイプをPOSTするときの例(/collection type)

ファイルだけアップロードするときとは違い、コレクションタイプのcreate APIにPOSTする形になります。
FormDataにファイルデータを追加する前に、一旦ファイル以外のデータをキー名'data'として、JSON文字列に変換して追加します。
ファイルデータは、キー名をfiles.{フィールド名}にして追加します。

ex) 画像のようなコレクションタイプに対してPOSTする場合

example.ts
    const body = new FormData();
    // Mediaタイプ以外のフィールドをdataに格納
    body.append('data', JSON.stringify({
      user_id: '01',
      text: 'aaaaaa',
    }));
    // ファイルをfiles.{フィールド名}に格納
    body.append('files.photo', fileObject);
    JSON.stringify(body);
    return this.http
      .post(environment.apiUrl + '/messages', body)
      .toPromise()
      .then((res) => {
        const response: any = res;
        return response;
      })
      .catch(this.errorHandler);
3
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
3
0