我正在尝试使用 API 和 tmhOAuth 请求将视频上传到 Twitter,但是我从 Twitter 收到错误:“片段加起来不等于提供的总文件大小。”。
我检查了块大小与 INIT 命令中提供的大小它们是相等的。你能帮我找到解决方案吗?
这是我用作基础的解决方案 https://stackoverflow.com/questions/32231642/uploading-videos-to-twitter-using-api
这是我的代码:
/**
* @param string $pathToVideo
*
* @return string
*
* @throws UploadException
* @throws \RuntimeException
*/
public function uploadVideo($pathToVideo)
{
//execute upload init and get media ID form init command
$mediaId = $this->init($pathToVideo);
//uploading video
$this->append($pathToVideo, $mediaId);
//finalize uploading
$code = $this->finalize($mediaId);
}
/**
* @param string $mediaId
*
* @return int
*/
private function finalize($mediaId)
{
return $this->sendPostRequest(['command' => 'FINALIZE', 'media_id' => $mediaId]);
}
/**
* @param string $pathToVideo
* @param string $mediaId
*
* @throws UploadException
*/
private function append($pathToVideo, $mediaId)
{
//read video file
$fp = fopen($pathToVideo, 'r');
//segment counter
$segmentId = 0;
$uploadedBytes = 0;
while (! feof($fp)) {
$chunk = fread($fp, self::CHUNK_LIMIT);
$uploadedBytes += strlen($chunk);
$code = $this->sendPostRequest([
'command' => 'APPEND',
'media_id' => $mediaId,
'media' => $chunk,
'segment_index' => $segmentId,
], true);
if (!in_array($code, [Response::HTTP_CONTINUE, Response::HTTP_NO_CONTENT], true)) {
throw new UploadException(sprintf(
"Uploading Twitter video failed during APPEND. Returned code %d.\nPath to video %s.\nResponse: %s",
$code,
$pathToVideo,
$this->tmhOAuth->response['response']
));
}
$segmentId++;
}
fclose($fp);
}
/**
* @param string $pathToVideo
*
* @return string
*
* @throws UploadException
*/
private function init($pathToVideo)
{
$fileSize = filesize($pathToVideo);
$code = $this->sendPostRequest([
'command' => 'INIT',
'total_bytes' => $fileSize,
'media_type' => 'video/mp4',
]);
$response = $this->tmhOAuth->response['response'];
if ($this->isSuccessCode($code)) {
//return media ID form init command
return json_decode($response)->media_id_string;
}
throw new UploadException(sprintf(
"Uploading Twitter video failed during INIT. Returned code %d.
Path to video %s, file size %d.\nEndpoint: " . $this->uploadUrl . "\nResponse %s",
$code,
$pathToVideo,
$fileSize,
$response
));
}
/**
* @param array $options
*
* @return int
*/
private function sendPostRequest($options, $isMultipart = false)
{
return $this->tmhOAuth->request(
'POST',
$this->uploadUrl,
$options,
true,
$isMultipart
);
}