Skip to main content

上传插件

¥Upload plugin

上传插件是 Strapi 管理面板中默认提供的媒体库的后端。上传插件是默认安装的,无法卸载。使用管理面板中的媒体库或直接使用上传 API,你可以上传任何类型的文件以在 Strapi 应用中使用。

¥The Upload plugin is the backend powering the Media Library available by default in the Strapi admin panel. The Upload plugin is installed by default and can not be uninstalled. Using either the Media Library from the admin panel or the upload API directly, you can upload any kind of file for use in your Strapi application.

默认情况下,Strapi 提供了 provider,用于将文件上传到本地目录,默认情况下,该目录将是 Strapi 项目中的 public/uploads/。如果你想将文件上传到其他位置,可以使用其他提供者。

¥By default Strapi provides a provider that uploads files to a local directory, which by default will be public/uploads/ in your Strapi project. Additional providers are available should you want to upload your files to another location.

Strapi 维护的提供者包括:

¥The providers maintained by Strapi include:

配置

¥Configuration

本节详细介绍默认上传提供程序的配置选项。如果使用其他提供者(例如 AWS S3 或 Cloudinary),请参阅该提供者文档中的可用配置参数。

¥This section details configuration options for the default upload provider. If using another provider (e.g. AWS S3 or Cloudinary), see the available configuration parameters in that provider's documentation.

本地服务器

¥Local server

默认情况下,Strapi 接受本地上传文件的 localServer 配置。这些将作为 koa-static 的选项传递。

¥By default Strapi accepts localServer configurations for locally uploaded files. These will be passed as the options for koa-static.

你可以通过创建或编辑 ./config/plugins.js 文件来提供它们。以下示例设置 max-age 标头。

¥You can provide them by creating or editing the ./config/plugins.js file. The following example sets the max-age header.

./config/plugins.js

module.exports = ({ env })=>({
upload: {
config: {
providerOptions: {
localServer: {
maxage: 300000
},
},
},
},
});

最大文件大小

¥Max file size

目前,除了传递给 sizeLimit 的上传插件的提供程序选项之外,负责解析请求的 Strapi 中间件还需要配置为支持大于默认值 200MB 的文件大小。

¥Currently the Strapi middleware in charge of parsing requests needs to be configured to support file sizes larger than the default of 200MB in addition to provider options passed to the upload plugin for sizeLimit.

提醒

你可能还需要调整任何上游代理、负载平衡器或防火墙以允许更大的文件大小。
(例如,Nginx 有一个名为 client_max_body_size 的配置设置,需要调整该设置,因为它的默认值仅为 1mb。)

¥You may also need to adjust any upstream proxies, load balancers, or firewalls to allow for larger file sizes.
(e.g. Nginx has a config setting called client_max_body_size that will need to be adjusted since it's default is only 1mb.)

我们使用的库是 koa-body,它使用 node-formidable 库来处理文件。

¥The library we use is koa-body, and it uses the node-formidable library to process files.

可以直接将配置传递给中间件,方法是在 ./config/middlewares.js 中的 body 中间件 配置中设置:

¥You can pass configuration to the middleware directly by setting it in the body middleware configuration in ./config/middlewares.js:

path: ./config/middlewares.js

module.exports = [
// ...
{
name: "strapi::body",
config: {
formLimit: "256mb", // modify form body
jsonLimit: "256mb", // modify JSON body
textLimit: "256mb", // modify text body
formidable: {
maxFileSize: 250 * 1024 * 1024, // multipart data, modify here limit of uploaded file size
},
},
},
// ...
];

除了中间件配置之外,还可以在 ./config/plugins.js 中的 插件配置 中传递 sizeLimit,它是一个以字节为单位的整数:

¥In addition to the middleware configuration, you can pass the sizeLimit, which is an integer in bytes, in the plugin configuration in ./config/plugins.js:

path: ./config/plugins.js

module.exports = {
// ...
upload: {
config: {
sizeLimit: 250 * 1024 * 1024 // 256mb in bytes
}
}
};

上传请求超时

¥Upload request timeout

默认情况下,strapi.server.httpServer.requestTimeout 的值设置为 330 秒。这包括上传。为了使互联网连接速度慢的用户能够上传大文件,可能需要增加此超时限制。建议的方法是在 config/server.js|ts 文件中设置 http.serverOptions.requestTimeout 参数(请参阅 服务器配置)。另一种方法是在 Strapi 启动之前运行的 bootstrap 函数中设置 requestTimeout 值。这在需要更改的情况下很有用 以编程方式 - 例如,暂时禁用并重新启用它:

¥By default, the value of strapi.server.httpServer.requestTimeout is set to 330 seconds. This includes uploads. To make it possible for users with slow internet connection to upload large files, it might be required to increase this timeout limit. The recommended way to do it is by setting the http.serverOptions.requestTimeout parameter in the config/server.js|ts file (see server configuration. An alternate method is to set the requestTimeout value in the bootstrap function that runs before Strapi gets started. This is useful in cases where it needs to change programmatically — for example, to temporarily disable and re-enable it:

path: ./index.js

module.exports = {

//...

bootstrap({ strapi }) {
// Set the requestTimeout to 1,800,000 milliseconds (30 minutes):
strapi.server.httpServer.requestTimeout = 30 * 60 * 1000;
},
};

响应式图片

¥Responsive Images

当在设置面板中启用 Enable responsive friendly upload 设置时,插件将生成以下响应式图片尺寸:

¥When the Enable responsive friendly upload setting is enabled in the settings panel the plugin will generate the following responsive image sizes:

名称最大尺寸
large1000 像素
medium750 像素
small500 像素

这些尺寸可以在 ./config/plugins.js 中被覆盖:

¥These sizes can be overridden in ./config/plugins.js:

path: ./config/plugins.js

module.exports = ({ env }) => ({
upload: {
config: {
breakpoints: {
xlarge: 1920,
large: 1000,
medium: 750,
small: 500,
xsmall: 64
},
},
},
});
提醒

断点更改仅适用于新图片,现有图片不会调整大小或生成新尺寸。

¥Breakpoint changes will only apply to new images, existing images will not be resized or have new sizes generated.

端点

¥Endpoints

方法路径描述
得到/api/upload/files获取文件列表
得到/api/upload/files/:id获取特定文件
邮政/api/upload上传文件
邮政/api/上传?id=x更新文件信息
删除/api/upload/files/:id删除文件
注意
  • 文件夹 是管理面板专用功能,不属于 Content API(REST 或 GraphQL)。通过 REST 上传的文件位于自动创建的 "API 上传" 文件夹中。

    ¥Folders are an admin panel-only feature and are not part of the Content API (REST or GraphQL). Files uploaded through REST are located in the automatically created "API Uploads" folder.

  • GraphQL API 不支持上传媒体文件。要上传文件,请使用 REST API 或直接从管理面板中的 媒体库 添加文件。仍然可以进行一些 GraphQL 修改来更新或删除已上传的媒体文件(有关详细信息,请参阅 GraphQL API 文档)。

    ¥The GraphQL API does not support uploading media files. To upload files, use the REST API or directly add files from the Media Library in the admin panel. Some GraphQL mutations to update or delete uploaded media files are still possible (see GraphQL API documentation for details).

示例

¥Examples

上传文件

¥Upload files

将一个或多个文件上传到你的应用。

¥Upload one or more files to your application.

接受以下参数:

¥The following parameters are accepted:

  • files:要上传的文件。该值可以是缓冲区或流。

    ¥files: The file(s) to upload. The value(s) can be a Buffer or Stream.

<form>

<input type="file" name="files" />
<input type="submit" value="Submit" />
</form>

<script type="text/javascript">
const form = document.querySelector('form');

form.addEventListener('submit', async (e) => {
e.preventDefault();

await fetch('/api/upload', {
method: 'post',
body: new FormData(e.target)
});
});
</script>
提醒

你必须在请求正文中发送 FormData。

¥You have to send FormData in your request body.

上传入口文件

¥Upload entry files

上传一个或多个将链接到特定条目的文件。

¥Upload one or more files that will be linked to a specific entry.

接受以下参数:

¥The following parameters are accepted:

范围描述
files要上传的文件。该值可以是缓冲区或流。
path(可选)文件将上传到的文件夹(仅在 Strapi-provider-upload-aws-s3 上受支持)。
refId文件将链接到的条目的 ID。
ref文件将链接到的模型的唯一 ID (uid)(请参阅下文)。
source(可选)模型所在插件的名称。
field文件将精确链接到的条目的字段。

例如,给定 Restaurant 模型属性:

¥For example, given the Restaurant model attributes:

path: ./src/api/restaurant/content-types/restaurant/schema.json

{
// ...
"attributes": {
"name": {
"type": "string"
},
"cover": {
"type": "media",
"multiple": false,
}
}
// ...
}

对应的代码是:

¥The corresponding code is be:

<form>

<input type="file" name="files" />
<input type="text" name="ref" value="api::restaurant.restaurant" />
<input type="text" name="refId" value="5c126648c7415f0c0ef1bccd" />
<input type="text" name="field" value="cover" />
<input type="submit" value="Submit" />
</form>

<script type="text/javascript">
const form = document.querySelector('form');

form.addEventListener('submit', async (e) => {
e.preventDefault();

await fetch('/api/upload', {
method: 'post',
body: new FormData(e.target)
});
});
</script>
提醒

你必须在请求正文中发送 FormData。

¥You have to send FormData in your request body.

型号定义

¥Models definition

将文件属性添加到模型(或另一个插件的模型)就像添加新的关联一样。

¥Adding a file attribute to a model (or the model of another plugin) is like adding a new association.

在下面的第一个示例中,你将能够上传一个文件并将其附加到头像属性。

¥In the first example below, you will be able to upload and attach one file to the avatar attribute.

path: ./src/api/restaurant/content-types/restaurant/schema.json

{
// ...
{
"attributes": {
"pseudo": {
"type": "string",
"required": true
},
"email": {
"type": "email",
"required": true,
"unique": true
},
"avatar": {
"type": "media",
"multiple": false,
}
}
}
// ...
}

在我们的第二个示例中,你可以上传并附加多张餐厅图片。

¥In our second example, you can upload and attach multiple pictures to the restaurant.

path: ./src/api/restaurant/content-types/restaurant/schema.json

{
// ...
{
"attributes": {
"name": {
"type": "string",
"required": true
},
"covers": {
"type": "media",
"multiple": true,
}
}
}
// ...
}

更新文件信息

¥Update fileInfo

更新应用中的文件。

¥Update a file in your application.

接受以下参数:

¥The following parameters are accepted:

  • fileInfo:要更新的文件信息。

    ¥fileInfo: The fileInfo to update.

import { FormData } from 'formdata-node';
import fetch from 'node-fetch';



const fileId = 50;




const newFileData = {


alternativeText: 'My new alternative text for this image!',
};



const form = new FormData();



form.append('fileInfo', JSON.stringify(newFileData));



const response = await fetch(`http://localhost:1337/api/upload?id=${fileId}`, {


method: 'post',
body: form,
});