如何上传文件

直接从代码把图像、HTML 和其他设计资源上传到 Stitch 项目。

磁盘上有模型图、截图或 HTML 原型?直接上传到 Stitch,把它变成屏幕——无需手动导入,无需浏览器,也没有 base64 编码的烦恼。

上传文件

import { stitch } from "@google/stitch-sdk";

const project = stitch.project("your-project-id");

const result = await project.upload("./mockup.png", {
  title: "Home Screen",
});

if (result.success) {
  const [screen] = result.screens;
  console.log(`Screen created: ${screen.id}`);
  const html = await screen.getHtml();
  const imageUrl = await screen.getImage();
}

SDK 会从磁盘读取文件,并直接发送到 Stitch REST API。这里不受输出令牌上限的约束——不像由智能体驱动的 MCP 调用那样会卡在 base64 编码的负载上。

支持的格式

扩展名类型屏幕类型
.png图像IMAGE
.jpg / .jpeg图像IMAGE
.webp图像IMAGE
.html / .htm文档DOCUMENT

HTML 文件会作为文档屏幕上传——适合导入现有网页或原型的静态快照。

选项

选项类型默认值说明
titlestring—屏幕在 Stitch 中显示的标题
createScreenInstancesbooleantrue是否将屏幕添加到画布

上传 HTML 原型

上传一个自包含的 HTML 文件,即可导入现有的设计:

const result = await project.upload("./prototype.html", {
  title: "Landing Page Prototype",
});

SDK 会自动识别 .html 和 .htm 扩展名,并把屏幕类型设为 DOCUMENT。

处理结果

upload() 从不抛出异常,而是返回一个可辨识联合的结果对象:

const result = await project.upload("./mockup.png");

if (result.success) {
  console.log(`Created ${result.screens.length} screens`);
} else {
  console.error(`${result.error.code}: ${result.error.message}`);
}

错误码

错误码含义
FILE_NOT_FOUND给定路径下不存在该文件
UNSUPPORTED_FORMAT扩展名不是 .png、.jpg、.jpeg、.webp、.html 或 .htm
AUTH_FAILEDAPI 密钥无效或缺失
UPLOAD_FAILED服务器拒绝了本次上传
UNKNOWN_ERROR意外失败

批量上传

在循环中上传多个文件:

import fs from "fs/promises";
import path from "path";

const project = stitch.project("your-project-id");
const files = await fs.readdir("./designs");

for (const file of files) {
  if (/\.(png|jpe?g|webp|html?)$/i.test(file)) {
    const result = await project.upload(
      path.join("./designs", file),
      { title: path.parse(file).name },
    );
    if (result.success) {
      console.log(`Uploaded ${file} → ${result.screens[0].id}`);
    }
  }
}

原文: https://stitch.withgoogle.com/docs/sdk/upload-image/

本页翻译自 Google Stitch 官方文档,原文版权归 Google LLC 所有。本站为独立第三方翻译,与 Google 无关联。