You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用TSL Mastodon API上传图片遇200状态却触发catch问题

问题分析与解决方案

核心问题1:forEach异步循环导致的执行顺序错误

你用forEach遍历图片URL并执行异步操作,但forEach不会等待内部的异步函数完成,这会引发两个问题:

  • 函数会在所有上传操作完成前就返回空的image_ids数组
  • 异步操作的错误处理脱离主函数控制,难以追踪完整执行流程

核心问题2:200状态码仍触发catch的原因

从错误输出里的"failed":true能看出,尽管HTTP响应状态是200,但TSL Mastodon API库内部判定请求失败。大概率是因为你传入的Blob不符合库的预期——多数Mastodon API客户端要求上传文件为File类型而非Blob。

修正后的代码

async MediaUpload(photos: any[]) {
    const client = await this.Login();
    const full_photo_urls: string[] = photos.map(item => item.full);
    const image_ids: string[] = [];

    // 用Promise.all处理所有异步上传,确保等待全部操作完成
    await Promise.all(full_photo_urls.map(async (image_url) => {
        try {
            const response = await fetch(image_url);
            // 将Blob转换为File类型,指定文件名和MIME类型
            const image_blob = await response.blob();
            const image_file = new File([image_blob], `upload_${Date.now()}.jpg`, {
                type: image_blob.type
            });

            console.log("准备上传图片!");
            const image_res = await client.postMediaAttachment({ file: image_file });
            console.log("图片上传完成");
            console.log(image_res);
            // 收集成功上传的媒体ID
            image_ids.push(image_res.json.id);
        } catch (error) {
            console.error("上传失败:", error);
        }
    }));

    return image_ids;
}

关键修改点

  • 替换forEach为Promise.all结合map,确保所有异步上传完成后再返回结果
  • 将Blob转换为File类型,匹配TSL Mastodon API对上传文件的格式要求
  • 保证image_ids能正确收集到上传成功的媒体ID
  • 统一错误处理逻辑,让报错信息更清晰

内容的提问来源于stack exchange,提问作者SkyMTF

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 04:53:21