php - 将图片/视频发布到 Twitter

标签 php twitter file-upload

当我尝试使用 Twitter API 发布图片或视频时,收到错误消息

{"request":"/i/media/upload.json","error":"Segments do not add up to provided total file size."}

Google 没有关于此错误的任何信息。 Twitter 文档也没有帮助。怎么了?

我在做什么:

1. INIT uploading file

> $this->SetUrl('upload.twitter.com/i/media/upload.json?command=INIT&media_type=image%2Fpng&total_bytes='
> . $filesize)
>                 ->SendRequest('post');

2. APPEND chunks

> $reply = ['media' => $chunk];
> $this->SetQuery($reply);
> $this->SetUrl('upload.twitter.com/i/media/upload.json?command=APPEND&media_id='.$mediaId.'&segment_index='.$segment_id)->SendRequest('post');

3. When I FINALIZE, I get the error

> $this->SetUrl('upload.twitter.com/i/media/upload.json?command=FINALIZE&media_id='
> . $mediaId)->SendRequest('post');

最佳答案

// APPEND
    $ch = curl_init();
    $file = fopen($media, 'r');
    $chunk_id = 0;

    while (!feof($file)) {

        $append_headers = array();
        $chunk = fread($file, 1048576); // 1mb per chunk
        $boundary = $chunk_id.time();
        $params  = "--" . $boundary . "\r\n"
            . "Content-Type: video/mp4\r\n"
            . "Content-Disposition: form-data; name=\"media\"; filename=\"blob\"\r\n"
            . "\r\n"
            . $chunk . "\r\n"
            . "--" . $boundary . "--";
        $append_headers[] = 'Content-Length: ' . strlen($params);
        $append_headers[] = 'Content-Type: multipart/form-data; boundary=' . $boundary;
        curl_setopt($ch, CURLOPT_HTTPHEADER, $append_headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        curl_setopt($ch, CURLOPT_USERAGENT, $this->curl_config['useragent']);
        curl_setopt($ch, CURLOPT_COOKIEJAR, $this->cookie_dir . md5($this->UserName . $this->Password));
        curl_setopt($ch, CURLOPT_COOKIEFILE, $this->cookie_dir . md5($this->UserName . $this->Password));
        curl_setopt($ch, CURLOPT_URL, 'https://upload.twitter.com/i/media/upload.json?command=APPEND&media_id=' . $init->media_id . '&segment_index=' . $chunk_id);
        $response = curl_exec($ch);
        $chunk_id++;

    }

这是我发布 block 的解决方案。效果很好。

关于php - 将图片/视频发布到 Twitter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34771079/

相关文章:

php - 保持一个php脚本一直运行

带有日期/时间和高图持续时间的 PHP 数组

php - 如何避免两个框架因重新声明函数而发生冲突?

php - iPhone Web 服务身份验证和访问 token

ios - Twitter API V1 仍在运行

iphone - ios 7.0 在ios模拟器中登录twitter问题

Java SE HTML POST 文件名问题

node.js - Twitter Stream 和 Node js 服务器错误

c# - WCF 添加服务失败。服务元数据可能无法访问。确保您的服务正在运行并公开元数据

android - 在android中上传文件以及其他字符串参数