文件存储
ShipAny 支持上传文件到 AWS S3 兼容的文件存储系统,例如 AWS S3 / Cloudflare R2 / 腾讯云 COS 等。
配置云存储
选择你的云存储平台,创建存储桶,设置访问密钥和访问域名。
然后把相关参数填写到项目的配置文件中:
.env
STORAGE_ENDPOINT = ""
STORAGE_REGION = ""
STORAGE_ACCESS_KEY = ""
STORAGE_SECRET_KEY = ""
STORAGE_BUCKET = ""
STORAGE_DOMAIN = ""
上传 AI 图片到云存储
把 aisdk 生成的图片(返回的 base64 数据),上传到云存储。
app/api/demo/gen-image/route.ts
import { newStorage } from "@/lib/storage";
const storage = new Storage();
const filename = `image_${new Date().getTime()}.png`;
const key = `shipany/${filename}`;
const body = Buffer.from(image.base64, "base64");
try {
const res = await storage.uploadFile({
body,
key,
contentType: "image/png",
disposition: "inline",
});
console.log("upload file success:", res);
} catch (err) {
console.log("upload file failed:", err);
}
uploadFile 接收的 body 参数是 Buffer 类型。你可以传递从 URL 下载的文件 Buffer 或者从本地文件读取的 Buffer。
读取本地文件上传到云存储
app/api/demo/gen-image/route.ts
import path from "path";
import { readFile } from "fs/promises";
import { newStorage } from "@/lib/storage";
const storage = newStorage();
const content = await readFile(path.join(process.cwd(), "sing.m4a"));
const res = await storage.uploadFile({
body: content,
key: `shipany/sing_${getUuid()}.mp3`,
contentType: "audio/mpeg",
});
注意:path 和 readFile 在 edge runtime 中无法使用,所以在 cloudflare 部署时,不能读取本地文件。
下载远程图片上传到云存储
给定一个远程的图片地址,下载图片并上传到云存储。
app/api/demo/gen-image/route.ts
import { newStorage } from "@/lib/storage";
const storage = newStorage();
const res = await storage.downloadAndUpload({
url: "https://shipany.ai/logo.png",
key: `shipany/logo.png`,
});