# 为 Strapi Cloud 上传提供商配置

> Source: https://strapi.nodejs.cn/cloud/advanced/upload

🌐 Upload Provider Configuration for Strapi Cloud

像 S3 或 Cloudinary 这样的外部存储需要插件设置、安全中间件和云变量。

Strapi Cloud 开箱即用带有本地上传提供者。不过，如果需要，它也可以配置为使用第三方上传提供者。

🌐 Strapi Cloud comes with a local upload provider out of the box. However, it can also be configured to use a third-party upload provider, if needed.

:::note

有关适用于上传的文件大小和基于内存的限制，请参见 [Strapi Cloud 上传大小限制](/cloud/advanced/upload-size-limits)。

🌐 For the file size and memory-based limits that apply to uploads, see [Upload size limits for Strapi Cloud](/cloud/advanced/upload-size-limits).

:::

## 配置第三方上传提供商 {#configuring-a-third-party-upload-provider}

🌐 Configuring a third-party upload provider

:::caution

请注意，Strapi 无法为第三方上传提供商提供支持。

🌐 Please be advised that Strapi is unable to provide support for third-party upload providers.

:::

:::prerequisites

- 一个在 `v4.8.2+` 上运行的本地 Strapi 项目。
- 第三方上传提供者的凭证（参见 [Strapi Market](https://market.strapi.io/providers)）。

:::

为在 Strapi Cloud 中使用第三方上传提供商进行配置，需要以下四个配置步骤，然后进行部署：

🌐 Configuring a third-party upload provider for use with Strapi Cloud requires the following 4 configuration steps, followed by a deployment:

1. 在本地 Strapi 项目中安装提供程序插件。
2. 在本地 Strapi 项目中配置提供者。
3. 在本地 Strapi 项目中配置安全中间件。
4. 将环境变量添加到 Strapi Cloud 项目中。

### 安装提供程序插件 {#install-the-provider-plugin}

🌐 Install the provider plugin

使用 `npm` 或 `yarn`，按照对应供应商在  [Marketplace](https://market.strapi.io/providers) 中的条目说明，将提供程序插件作为包依赖安装到本地 Strapi 项目中。

### 配置提供程序 {#configure-the-provider}

🌐 Configure the provider

要在你的 Strapi 项目中配置第三方上传提供商，请通过以下方式创建或编辑生产环境 `/config/env/production/plugins.js|ts` 的插件配置文件，添加上传配置选项如下：

🌐 To configure a third-party upload provider in your Strapi project, create or edit the plugins configuration file for your production environment `/config/env/production/plugins.js|ts` by adding upload configuration options as follows:

```js title=/config/env/production/plugins.js

module.exports = ({ env }) => ({
// … some unrelated plugins configuration options
// highlight-start
upload: {
   config: {
      // … provider-specific upload configuration options go here
   }
// highlight-end
// … some other unrelated plugins configuration options
}
});
```
```ts title=/config/env/production/plugins.ts

// … some unrelated plugins configuration options
// highlight-start
upload: {
   config: {
      // … provider-specific upload configuration options go here
   }
// highlight-end
// … some other unrelated plugins configuration options
}
});
```

:::caution

文件结构必须与上述路径完全匹配，否则配置将不会应用到 Strapi 云。

🌐 The file structure must match the above path exactly, or the configuration will not be applied to Strapi Cloud.

:::

每个提供商将有不同的配置设置可用。请查看 [Marketplace](https://market.strapi.io/providers)中该提供商的相应条目。

**示例:**
<Tabs groupId="js-ts">
<TabItem value="js" label="JavaScript">
<Tabs groupId="upload-examples" >
<TabItem value="cloudinary" label="Cloudinary">

```js title=/config/env/production/plugins.js
module.exports = ({ env }) => ({
  // ...
  upload: {
    config: {
      provider: 'cloudinary',
      providerOptions: {
        cloud_name: env('CLOUDINARY_NAME'),
        api_key: env('CLOUDINARY_KEY'),
        api_secret: env('CLOUDINARY_SECRET'),
      },
      actionOptions: {
        upload: {},
        uploadStream: {},
        delete: {},
      },
    },
  },
  // ...
});
```

</TabItem >
:::tip

有关完整的 S3 提供程序配置详情（凭证格式、扩展选项、兼容 S3 的服务），请参阅 CMS 文档中的 [Amazon S3 提供程序](/cms/configurations/media-library-providers/amazon-s3) 页面。

🌐 For full S3 provider configuration details (credential formats, extended options, S3-compatible services), see the [Amazon S3 provider](/cms/configurations/media-library-providers/amazon-s3) page in the CMS documentation.

:::

```js title=/config/env/production/plugins.js
module.exports = ({ env }) => ({
  // ...
  upload: {
    config: {
      provider: 'aws-s3',
      providerOptions: {
        baseUrl: env('CDN_URL'),
        rootPath: env('CDN_ROOT_PATH'),
        s3Options: {
          credentials: {
            accessKeyId: env('AWS_ACCESS_KEY_ID'),
            secretAccessKey: env('AWS_ACCESS_SECRET'),
          },
          region: env('AWS_REGION'),
          params: {
            ACL: env('AWS_ACL', 'public-read'),
            signedUrlExpires: env('AWS_SIGNED_URL_EXPIRES', 15 * 60),
            Bucket: env('AWS_BUCKET'),
          },
        },
      },
      actionOptions: {
        upload: {},
        uploadStream: {},
        delete: {},
      },
    },
  },
  // ...
});
```

<TabItem value="ts" label="TypeScript">
<Tabs groupId="upload-examples" >
<TabItem value="cloudinary" label="Cloudinary">

```ts title=/config/env/production/plugins.ts

  // ...
  upload: {
    config: {
      provider: 'cloudinary',
      providerOptions: {
        cloud_name: env('CLOUDINARY_NAME'),
        api_key: env('CLOUDINARY_KEY'),
        api_secret: env('CLOUDINARY_SECRET'),
      },
      actionOptions: {
        upload: {},
        uploadStream: {},
        delete: {},
      },
    },
  },
  // ...
});
```

</TabItem >
```ts title=/config/env/production/plugins.ts

  // ...
  upload: {
    config: {
      provider: 'aws-s3',
      providerOptions: {
        baseUrl: env('CDN_URL'),
        rootPath: env('CDN_ROOT_PATH'),
        s3Options: {
          credentials: {
            accessKeyId: env('AWS_ACCESS_KEY_ID'),
            secretAccessKey: env('AWS_ACCESS_SECRET'),
          },
          region: env('AWS_REGION'),
          params: {
            ACL: env('AWS_ACL', 'public-read'),
            signedUrlExpires: env('AWS_SIGNED_URL_EXPIRES', 15 * 60),
            Bucket: env('AWS_BUCKET'),
          },
        },
      },
      actionOptions: {
        upload: {},
        uploadStream: {},
        delete: {},
      },
    },
  },
  // ...
});
```

### 配置安全中间件 {#configure-the-security-middleware}

🌐 Configure the security middleware

由于 Strapi 安全中间件的默认设置，你需要修改 `contentSecurityPolicy` 设置才能在媒体库中正确查看缩略图预览。

🌐 Due to the default settings in the Strapi security middleware you will need to modify the `contentSecurityPolicy` settings to properly see thumbnail previews in the Media Library.

:::caution

在 Strapi Cloud 上，`NODE_ENV` 始终设置为 `production`。对全局 `config/middlewares.ts` 文件的更改会在每次部署时被覆盖，因此不会生效。请将你的安全中间件自定义放在 `config/env/production/middlewares.ts` 中。详情请参见 [Strapi Cloud 的中间件配置](/cloud/advanced/middlewares)。

🌐 On Strapi Cloud, `NODE_ENV` is always set to `production`. Changes to the global `config/middlewares.ts` file are overwritten on each deploy and will not take effect. Place your Security Middleware customizations in `config/env/production/middlewares.ts` instead. See [Middleware Configuration for Strapi Cloud](/cloud/advanced/middlewares) for details.

:::

在你的 Strapi 项目中执行此操作：

🌐 To do this in your Strapi project:

1. 在你的 Strapi 项目中，导航到 `/config/env/production/middlewares.js` 或 `/config/env/production/middlewares.ts`。
2. 用上传提供者提供的对象替换默认的 `strapi::security` 字符串。

**示例:**
```js title=/config/env/production/middlewares.js
module.exports = [
  // ...
  {
    name: 'strapi::security',
    config: {
      contentSecurityPolicy: {
        useDefaults: true,
        directives: {
          'connect-src': ["'self'", 'https:'],
          'img-src': [
            "'self'", 
            'data:', 
            'blob:', 
            'market-assets.strapi.io', 
            'res.cloudinary.com'
          ],
          'media-src': [
            "'self'",
            'data:',
            'blob:',
            'market-assets.strapi.io',
            'res.cloudinary.com',
          ],
          upgradeInsecureRequests: null,
        },
      },
    },
  },
  // ...
];
```
```js title=/config/env/production/middlewares.js
module.exports = [
  // ...
  {
    name: 'strapi::security',
    config: {
      contentSecurityPolicy: {
        useDefaults: true,
        directives: {
          'connect-src': ["'self'", 'https:'],
          'img-src': [
            "'self'",
            'data:',
            'blob:',
            'market-assets.strapi.io',
            'yourBucketName.s3.yourRegion.amazonaws.com',
          ],
          'media-src': [
            "'self'",
            'data:',
            'blob:',
            'market-assets.strapi.io',
            'yourBucketName.s3.yourRegion.amazonaws.com',
          ],
          upgradeInsecureRequests: null,
        },
      },
    },
  },
  // ...
];
```
```ts title=/config/env/production/middlewares.ts

  // ...
  {
    name: 'strapi::security',
    config: {
      contentSecurityPolicy: {
        useDefaults: true,
        directives: {
          'connect-src': ["'self'", 'https:'],
          'img-src': [
            "'self'", 
            'data:', 
            'blob:', 
            'market-assets.strapi.io', 
            'res.cloudinary.com'
          ],
          'media-src': [
            "'self'",
            'data:',
            'blob:',
            'market-assets.strapi.io',
            'res.cloudinary.com',
          ],
          upgradeInsecureRequests: null,
        },
      },
    },
  },
  // ...
];
```
```ts title=/config/env/production/middlewares.ts

  // ...
  {
    name: 'strapi::security',
    config: {
      contentSecurityPolicy: {
        useDefaults: true,
        directives: {
          'connect-src': ["'self'", 'https:'],
          'img-src': [
            "'self'",
            'data:',
            'blob:',
            'market-assets.strapi.io',
            'yourBucketName.s3.yourRegion.amazonaws.com',
          ],
          'media-src': [
            "'self'",
            'data:',
            'blob:',
            'market-assets.strapi.io',
            'yourBucketName.s3.yourRegion.amazonaws.com',
          ],
          upgradeInsecureRequests: null,
        },
      },
    },
  },
  // ...
];
```

:::tip

在将上述更改推送到 GitHub 之前，向 Strapi Cloud 项目添加环境变量，以防在更改完成之前触发项目的重建和新部署。

🌐 Before pushing the above changes to GitHub, add environment variables to the Strapi Cloud project to prevent triggering a rebuild and new deployment of the project before the changes are complete.

:::

### Strapi 云配置 {#strapi-cloud-configuration}

🌐 Strapi Cloud configuration

1. 登录 Strapi Cloud，然后在“项目”页面上点击相应的项目。
2. 点击 **设置** 标签，然后在左侧菜单中选择 **变量**。
3. 添加特定于上传提供者的所需环境变量。
4. 点击 **保存**。

**示例：**

| 变量 | 值 |
|---------------------|-------------------------|
| `CLOUDINARY_NAME` | your_cloudinary_name |
| `CLOUDINARY_KEY` | your_cloudinary_api_key |
| `CLOUDINARY_SECRET` | your_cloudinary_secret |
| 变量 | 值 |
|---------------------|------------------------|
| `AWS_ACCESS_KEY_ID` | 你的_aws_access_key_id |
| `AWS_ACCESS_SECRET` | 你的_aws_access_secret |
| `AWS_REGION` | 你的_aws_region |
| `AWS_BUCKET` | 你的_aws_bucket |
| `CDN_URL` | 你的_cdn_url |
| `CDN_ROOT_PATH` | 你的_cdn_root_path |

### 部署 {#deployment}

🌐 Deployment

要部署项目并使用第三方上传提供商，请推送之前的更改。这将触发 Strapi Cloud 项目的重新构建和新部署。

🌐 To deploy the project and use the third-party upload provider, push the changes from earlier. This will trigger a rebuild and new deployment of the Strapi Cloud project.

一旦应用构建完成，项目将使用新的上传提供者。

🌐 Once the application finishes building, the project will use the new upload provider.

:::strapi Custom Provider

如果你想创建自定义上传提供程序，请参阅 CMS 文档中的 [Providers](/cms/features/media-library#providers) 文档。

🌐 If you want to create a custom upload provider, please refer to the [Providers](/cms/features/media-library#providers) documentation in the CMS Documentation.

:::
