如何上傳檔案
直接從程式碼將圖像、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 | IMAGE |
.jpg / .jpeg | Image | IMAGE |
.webp | Image | IMAGE |
.html / .htm | Document | DOCUMENT |
HTML 檔案會以文件螢幕的形式上傳——很適合匯入現有網頁或原型的靜態快照。
選項
| 選項 | 型別 | 預設值 | 說明 |
|---|---|---|---|
title | string | — | 螢幕在 Stitch 中的顯示標題 |
createScreenInstances | boolean | true | 是否將螢幕加入畫布 |
上傳 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_FAILED | API 金鑰無效或缺少 |
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 無關聯。