上传处理
上传处理在图片写入存储前同步执行,适合压缩尺寸、转换格式、加水印或在保存前自动归类。这一步产出的图片会成为最终保存的原图。
完整示例
下面的示例使用宿主提供的 services.images.sharp,把超过 1280px 宽的静态图片缩小,并支持通过请求参数 width 临时覆盖宽度:
ts
import { Readable } from "node:stream";
import {
definePlugin,
PluginError,
withAbortSignal,
} from "@picloom/plugin-sdk";
export default definePlugin({
id: "example.resize",
version: "1.0.0",
kind: "processor",
defaultLocale: "en-US",
messages: {
"en-US": {
"package.name": "Example resize",
"settings.width.label": "Maximum width",
},
"zh-CN": { "package.name": "缩放示例", "settings.width.label": "最大宽度" },
},
stages: {
upload: {
configSchemaVersion: 1,
configSchema: {
type: "object",
properties: {
width: {
"x-ui": { labelKey: "settings.width.label" },
type: "integer",
minimum: 1,
default: 1280,
},
},
required: ["width"],
additionalProperties: false,
},
paramsSchema: {
type: "object",
properties: {
width: { type: "integer", minimum: 1, maximum: 8192 },
},
additionalProperties: false,
},
async createInstance({ config, services }) {
return {
async process({ file, params, limits, writeOutput }, { signal }) {
if (
file.metadata.animated ||
!["image/jpeg", "image/png", "image/webp"].includes(
file.metadata.mimeType ?? "",
)
)
return {
status: "unsupported",
reason: "Only static JPEG, PNG and WebP images are supported",
};
const width = params.width ?? config.width;
if (width > limits.maxDimension)
throw new PluginError(
"RESOURCE_LIMIT",
"Width exceeds processing limit",
);
signal.throwIfAborted();
const bytes = await file.readBytes();
// Sharp is supplied by the host; the package does not bundle its own copy.
const image = services.images
.sharp(bytes, { limitInputPixels: limits.maxPixels })
.rotate()
.resize({ width, withoutEnlargement: true })
.toFormat(
file.metadata.mimeType === "image/jpeg"
? "jpeg"
: file.metadata.mimeType === "image/webp"
? "webp"
: "png",
);
const output = await withAbortSignal(image, signal, () =>
writeOutput(
Readable.toWeb(image) as unknown as ReadableStream<Uint8Array>,
),
);
signal.throwIfAborted();
return { status: "replace", output };
},
};
},
},
},
});安装后,在后台创建上传处理链并添加 缩放示例,绑定到上传配置即可验证。
接口说明
ts
process(
input: UploadProcessInput,
context: UploadProcessContext,
): Promise<UploadResult>;输入
| 字段 | 说明 |
|---|---|
params | 本次上传传入且已在处理链步骤中开放的请求参数(不含固定配置) |
file | 当前图片,读元数据用 file.metadata,读内容用 file.openRead() 或 file.readBytes() |
record | 当前文件身份、归属和归类信息 |
limits | { maxDimension: number; maxPixels: number },宿主配置的宽高和总像素上限,传给 Sharp 等解码器防大图炸内存 |
writeOutput(source) | (source: ReadableStream<Uint8Array> | Uint8Array) => Promise<OutputToken>,写入替换后的图片字节或流,异步返回不透明令牌 OutputToken(非大文件可直接传 await image.toBuffer(),免去流转换) |
context 除了 signal、requestId、log 和步骤间临时共享的 data,还提供 context.organization 用来查找或创建注册用户的标签与集合(详见文件上下文与归类)。
返回值
ts
type UploadResult =
| { status: "pass"; organization?: OrganizationUpdate }
| { status: "replace"; output: OutputToken; organization?: OrganizationUpdate }
| { status: "reject"; reason: string }
| { status: "unsupported"; reason?: string };status | 宿主行为 |
|---|---|
pass | 保持当前图片不变,进入下一步 |
replace | 用本次 await writeOutput(...) 返回的 output 替换当前图片,进入下一步 |
reject | 业务拒绝,直接中止上传并返回 reason |
unsupported | 当前图片不适用(如动图),按步骤配置决定跳过还是中止 |
- 设置归类:
organization: { tagIds?, collectionIds? }对传入的字段执行整项覆盖(省略某个字段则保留原值,传[]则清空;若想在保留已有标签的基础上追加新标签,请合并[...record.organization.tags.map((t) => t.id), newTag.id])。每项最多 100 个 ID,仅限注册用户自己的分类。 - 执行出错:网络、IO 或内部异常抛出
PluginError,不要伪装成unsupported。