我正试图实现从服务器上传视频到YouTube,但我有问题。我使用Laravel 9
和谷歌API客户端php
。代码是这样的,和google的例子差不多:
public function goToAuthUrl() {
$client = new Client();
$client->setApplicationName('Test');
$client->setScopes([
YouTube::YOUTUBE_UPLOAD,
]);
$client->setAuthConfig('client_secret_***.apps.googleusercontent.com.json');
$client->setAccessType('offline');
$authUrl = $client->createAuthUrl();
return redirect()->away($authUrl);
}
public function youtubeHandle(Request $request) {
session_start();
$htmlBody = '';
$client = new Google_Client();
$client->setAuthConfigFile('client_secret_***.apps.googleusercontent.com.json');
$client->setRedirectUri('https://***/youtube');
$client->addScope(YouTube::YOUTUBE_UPLOAD);
if (!isset($request->code)) {
$auth_url = $client->createAuthUrl();
} else {
$accessToken = $client->fetchAccessTokenWithAuthCode($request->code);
$client->setAccessToken($accessToken);
try{
$videoPath = url('storage/images/rain.mp4');
// Define an object that will be used to make all API requests.
$youtube = new Google_Service_YouTube($client);
$snippet = new Google_Service_YouTube_VideoSnippet();
$snippet->setTitle("Test title");
$snippet->setDescription("Test description");
$snippet->setTags(array("test"));
// Numeric video category.
$snippet->setCategoryId(27);
// Set the video's status to "public". Valid statuses are "public",
// "private" and "unlisted".
$status = new Google_Service_YouTube_VideoStatus();
$status->privacyStatus = "unlisted";
// Associate the snippet and status objects with a new video resource.
$video = new Google_Service_YouTube_Video();
$video->setSnippet($snippet);
$video->setStatus($status);
// Specify the size of each chunk of data, in bytes. Set a higher value for
// reliable connection as fewer chunks lead to faster uploads. Set a lower
// value for better recovery on less reliable connections.
$chunkSizeBytes = 1 * 1024 * 1024;
// Setting the defer flag to true tells the client to return a request which can be called
// with ->execute(); instead of making the API call immediately.
$client->setDefer(true);
// Create a request for the API's videos.insert method to create and upload the video.
$insertRequest = $youtube->videos->insert("status,snippet", $video);
// Create a MediaFileUpload object for resumable uploads.
$media = new Google_Http_MediaFileUpload(
$client,
$insertRequest,
'video/*',
null,
true,
$chunkSizeBytes
);
$media->setFileSize(Storage::size('public/images/rain.mp4'));
// Read the media file and upload it chunk by chunk.
$status = false;
$handle = fopen($videoPath, "rb");
while (!$status && !feof($handle)) {
$chunk = fread($handle, $chunkSizeBytes);
$status = $media->nextChunk($chunk);
}
fclose($handle);
// If you want to make other calls after the file upload, set setDefer back to false
$client->setDefer(false);
$htmlBody .= "<h3>Video Uploaded</h3><ul>";
$htmlBody .= sprintf('<li>%s (%s)</li>',
$status['snippet']['title'],
$status['id']);
$htmlBody .= '</ul>';
} catch (Google_Service_Exception $e) {
$htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
} catch (Google_Exception $e) {
$htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
}
$_SESSION['token'] = $client->getAccessToken();
}
echo $htmlBody;
所以,oauth
进程进展顺利,首先我运行goToAuthUrl()
函数,给予权限,它将我重定向回网站并运行youtubeHandle()
函数。这里有一些问题。它抛出一个错误
Invalid request. The number of bytes uploaded is required to be equal or greater than 262144, except for the final request (it's recommended to be the exact multiple of 262144). The received request contained 16098 bytes, which does not meet this requirement.
指向$status = $media->nextChunk($chunk);
。
我试图找到解决方案并更改代码,如将$insertRequest
变量更改为:
$insertRequest = $youtube->videos->insert("status,snippet", $video, [
'data' => file_get_contents(url('storage/images/rain.mp4')),
'mimeType' => 'video/*',
'uploadType' => 'multipart'
]);
这样会抛出另一个错误
Failed to start the resumable upload (HTTP 200)
和没有在频道上创建视频。
你能告诉我问题在哪里吗?
我再次强调,提出问题是得到答案的一半。我找到了一个解决方案,我使用的例子是旧的,但它在文档中。如果有人遇到这个问题-这都是关于块的,有一个函数来获取它:
private function readVideoChunk($handle, $chunkSize) {
$byteCount = 0;
$giantChunk = "";
while (!feof($handle)) {
// fread will never return more than 8192 bytes if the stream is read
// buffered and it does not represent a plain file
$chunk = fread($handle, 8192);
$byteCount += strlen($chunk);
$giantChunk .= $chunk;
if ($byteCount >= $chunkSize) {
return $giantChunk;
}
}
return $giantChunk;
}
上传应该是这样的:
// Read the media file and upload it chunk by chunk.
$status = false;
$handle = fopen($videoPath, "rb");
while (!$status && !feof($handle)) {
$chunk = $this->readVideoChunk($handle, $chunkSizeBytes);
$status = $media->nextChunk($chunk);
}