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

能否直接将S3 CDN链接传给Twitter API v1视频上传接口?

Twitter API v1 视频上传:直接拉取方案与流程优化

结论先行

Twitter API v1 的 POST media/upload (append) 接口不支持直接传入外部S3链接让平台自动拉取视频,必须由你的服务主动将视频数据分片上传。

优化现有流程(不用全量存Buffer)

你当前的代码会把整个视频加载到内存里,大视频容易爆内存。可以改成流式分片上传,直接把S3返回的数据流转发给Twitter,不用缓存全量数据:

优化后的代码示例

import axios from 'axios';

// 流式转发S3视频到Twitter分片上传接口
const streamUploadToTwitter = async (s3Url: string, mediaId: string, chunkSize = 5 * 1024 * 1024) => {
  // 先从S3获取视频流
  const s3StreamRes = await axios({
    method: 'GET',
    url: s3Url,
    responseType: 'stream',
  });

  let offset = 0;
  let tempBuffer = Buffer.alloc(0);

  return new Promise<void>((resolve, reject) => {
    s3StreamRes.data.on('data', async (chunk: Buffer) => {
      tempBuffer = Buffer.concat([tempBuffer, chunk]);
      
      // 攒够分片大小就上传
      while (tempBuffer.length >= chunkSize) {
        const uploadChunk = tempBuffer.slice(0, chunkSize);
        tempBuffer = tempBuffer.slice(chunkSize);
        
        await axios.post(
          'https://upload.twitter.com/1.1/media/upload.json',
          {
            command: 'APPEND',
            media_id: mediaId,
            segment_index: Math.floor(offset / chunkSize),
            media: uploadChunk,
          },
          {
            headers: {
              'Content-Type': 'application/octet-stream',
              // 替换为你的Twitter API认证头,比如 Authorization: Bearer xxx 或 OAuth 头
            },
          }
        );
        
        offset += chunkSize;
      }
    });

    // 处理剩余的最后一块数据
    s3StreamRes.data.on('end', async () => {
      if (tempBuffer.length > 0) {
        await axios.post(
          'https://upload.twitter.com/1.1/media/upload.json',
          {
            command: 'APPEND',
            media_id: mediaId,
            segment_index: Math.floor(offset / chunkSize),
            media: tempBuffer,
          },
          {
            headers: {
              'Content-Type': 'application/octet-stream',
              // 认证头
            },
          }
        );
      }
      // 最后调用FINALIZE完成上传
      await axios.post(
        'https://upload.twitter.com/1.1/media/upload.json',
        { command: 'FINALIZE', media_id: mediaId },
        { headers: { /* 认证头 */ } }
      );
      resolve();
    });

    s3StreamRes.data.on('error', (err) => {
      console.error('传输出错:', err);
      reject(err);
    });
  });
};

可选替代方案:切换到Twitter API v2

如果业务允许升级到API v2,POST /2/media/upload 接口支持直接传入公网可访问的视频URL(比如你的S3 CDN链接),通过source_url参数提交,由Twitter自行拉取处理,流程会简单很多。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 07:27:11