我正在尝试使用PHP将视频上传到Youtube . 我正在使用Youtube API v3,我正在使用最新检出的Google API PHP客户端库源代码 .
我正在使用给出的示例代码
https://code.google.com/p/google-api-php-client/执行身份验证 . 身份验证很顺利,但是当我尝试上传视频时,我得到 Google_ServiceException
,错误代码为500,消息为null .
我看了之前提到的以下问题:Upload video to youtube using php client library v3但是接受的答案没有描述如何指定要上传的文件数据 .
我发现了另一个类似的问题Uploading file with Youtube API v3 and PHP,其中在评论中提到categoryId是强制性的,因此我尝试在片段中设置categoryId,但它仍然给出相同的异常 .
我还提到了文档站点上的Python代码(https://developers.google.com/youtube/v3/docs/videos/insert),但我在客户端库中找不到函数next_chunk . 但我试图在循环(在代码片段中提到)重试获取错误代码500,但在所有10次迭代中我得到相同的错误 .
以下是我正在尝试的代码段:
$youTubeService = new Google_YoutubeService($client);
if ($client->getAccessToken()) {
print "Successfully authenticated";
$snippet = new Google_VideoSnippet();
$snippet->setTitle = "My Demo title";
$snippet->setDescription = "My Demo descrition";
$snippet->setTags = array("tag1","tag2");
$snippet->setCategoryId(23); // this was added later after refering to another question on stackoverflow
$status = new Google_VideoStatus();
$status->privacyStatus = "private";
$video = new Google_Video();
$video->setSnippet($snippet);
$video->setStatus($status);
$data = file_get_contents("video.mp4"); // This file is present in the same directory as the code
$mediaUpload = new Google_MediaFileUpload("video/mp4",$data);
$error = true;
$i = 0;
// I added this loop because on the sample python code on the documentation page
// mentions we should retry if we get error codes 500,502,503,504
$retryErrorCodes = array(500, 502, 503, 504);
while($i < 10 && $error) {
try{
$ret = $youTubeService->videos->insert("status,snippet",
$video,
array("data" => $data));
// tried the following as well, but even this returns error code 500,
// $ret = $youTubeService->videos->insert("status,snippet",
// $video,
// array("mediaUpload" => $mediaUpload);
$error = false;
} catch(Google_ServiceException $e) {
print "Caught Google service Exception ".$e->getCode()
. " message is ".$e->getMessage();
if(!in_array($e->getCode(), $retryErrorCodes)){
break;
}
$i++;
}
}
print "Return value is ".print_r($ret,true);
// We're not done yet. Remember to update the cached access token.
// Remember to replace $_SESSION with a real database or memcached.
$_SESSION['token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
print "<a href='$authUrl'>Connect Me!</a>";
}
这是我做错了吗?
4 回答
我能够使用以下代码使上传工作:
我意识到这是旧的,但这是文档的答案:
我也意识到这是旧的, but 因为我从GitHub克隆了最新版本的php-client,我遇到了麻烦
Google_Service_YouTube_Videos_Resource::insert()
-method .我会传递一个数组,其中
"data" => file_get_contents($pathToVideo)
和"mimeType" => "video/mp4"
设置为insert()
-method的参数,但我仍然继续获得 (400) BadRequest .通过
\Google\Service\Resource.php
中找到的Google代码进行调试和阅读,对数组密钥"uploadType"
进行了检查(在第179-180行),这将启动Google_Http_MediaFielUpload对象 .如果我没记错的话,使用PHP-api的0.6版本就不需要uploadType参数 . 这可能仅适用于直接上传样式,而不适用于任何一天的答案中显示的可恢复上传 .
答案是通过Google PHP client libraries使用Google_Http_MediaFileUpload .
这是示例代码:https://github.com/youtube/api-samples/blob/master/php/resumable_upload.php