Files
browser/platform_web/utils/serverFileTransfer.ts
T

43 lines
1.8 KiB
TypeScript

import type { PlatformApiClient } from "../api/client";
import type { ServerFileDownloadResponse } from "../api/types";
export async function downloadServerFileResult(client: PlatformApiClient, result: ServerFileDownloadResponse): Promise<string> {
if (result.status !== "ready") {
return result.reason ?? "文件读取任务已派发,完成后可再次下载。";
}
if (result.content !== undefined) {
saveBlob(new Blob([result.content], { type: result.contentType ?? "text/plain;charset=utf-8" }), result.filename || "server-file.txt");
return `下载已开始:${result.filename || result.key}`;
}
if (!result.artifact) {
return "文件内容尚未可用。";
}
const chunks: ArrayBuffer[] = [];
let offset = 0;
const chunkSize = Math.max(1, result.artifact.chunkSizeBytes || 1024 * 1024);
while (offset < result.artifact.sizeBytes) {
const chunk = await client.readArtifactContent(result.artifact.artifactId, offset, Math.min(chunkSize, result.artifact.sizeBytes - offset));
chunks.push(chunk.payload);
offset += chunk.contentLength;
if (chunk.contentLength <= 0) break;
}
saveBlob(new Blob(chunks, { type: result.artifact.contentType || "application/octet-stream" }), result.filename || result.artifact.filename);
return `下载已开始:${result.filename || result.artifact.filename}`;
}
function saveBlob(blob: Blob, filename: string) {
const url = URL.createObjectURL(blob);
const anchor = document.createElement("a");
anchor.href = url;
anchor.download = safeFilename(filename);
document.body.appendChild(anchor);
anchor.click();
anchor.remove();
window.setTimeout(() => URL.revokeObjectURL(url), 1000);
}
function safeFilename(filename: string): string {
const cleaned = filename.replace(/[\\/:*?"<>|]+/g, "-").trim();
return cleaned || "server-file.txt";
}