使用Youtube API v3和PHP上传文件 [英] Uploading file with Youtube API v3 and PHP

查看:70
本文介绍了使用Youtube API v3和PHP上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用新的api v3将文件上传到youtube.这就是我的工作...

I'm trying to upload a file to youtube using the new api v3. Here's what I do...

public function upload(){

    if(isset($_FILES['userfile'])) {

        $snippet = new Google_VideoSnippet();

        $snippet->setTitle("Test v3");
        $snippet->setDescription("First upload using api v3");
        $snippet->setTags(array("api","v3"));

        $video = new Google_Video();
        $video->setSnippet($snippet);

            $response = $this->googleapi->youtube->videos->insert(
                "status,snippet",
                $video,
                array('data' => $_FILES['userfile']['tmp_name'])
                );

            var_dump($response);

  }else{
    $this->load->view('youtube');
  }
}

响应为空,因为 io/Google_REST.php 抛出

第70行的未定义索引:错误"

'Undefined index: errors' at line 70

位于 decodeHttpResponse()

但是,从 Google_Client :: $ io-> makeRequest()的实际响应中转储会返回以下内容...

however, a dump from the actual response of Google_Client::$io->makeRequest() returns the following...

object(Google_HttpRequest)#31 (10) { ["batchHeaders":"Google_HttpRequest":private]=>  
array(4) { ["Content-Type"]=>  string(16) "application/http" ["Content-Transfer-Encoding"]=>
string(6) "binary" ["MIME-Version"]=>  string(3) "1.0" ["Content-Length"]=>  string(0) "" }
["url":protected]=>  string(197) "https://www.googleapis.com/upload/youtube
/v3/videos?part=status%2Csnippet&uploadType=multipart&
key=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" 
["requestMethod":protected]=>  string(4) "POST" ["requestHeaders":protected]=>  
array(3) { ["content-type"]=>  string(37) "multipart/related; boundary=131050532"
["authorization"]=>  string(64) "BearerXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 
["content-length"]=> int(254) } ["postBody":protected]=>  string(254) 
"--131050532 Content-Type: application/json; charset=UTF-8 {"snippet":{"tags": 
["api","v3"],"title":"Test v3","description":"First upload using api v3"}} --131050532  
Content-Type: Content-Transfer-Encoding: base64 c2FtcGxlLm1wNA== --131050532--"  
["userAgent":protected]=>  string(44) "Youtube test app google-api-php-client/0.6.0"  
["responseHttpCode":protected]=>  int(500) ["responseHeaders":protected]=>  array(7) {  
["server"]=>  string(61) "HTTP Upload Server Built on Dec 12 2012 15:53:08 (1355356388)"  
["content-type"]=>  string(16) "application/json" ["date"]=>  string(29) "Wed, 19 Dec 2012  
13:03:00 GMT" ["pragma"]=>  string(8) "no-cache" ["expires"]=>  string(29) "Fri, 01 Jan 1990 
00:00:00 GMT" ["cache-control"]=>  string(35) "no-cache, no-store, must-revalidate" ["content-
length"]=>  string(2) "52" } ["responseBody":protected]=>  string(52) "{ "error": { "code": 500, 
"message": null } } " ["accessKey"]=>  NULL }

在此方面的任何帮助将不胜感激.

Any help moving forwards with this would be greatly appreciated.

推荐答案

阅读示例这就是实际工作!"和结束工作!":

Read example between "this is the work in action!" and "end Work!":

<?php
@session_start();

if(!isset($_SESSION['google']))
    $_SESSION['google'] = array('state'=> null, 'token'=> null);

#include core google
set_include_path(get_include_path() . PATH_SEPARATOR . '/Google');
require_once  'Google/autoload.php';

$redirectUri = 'http://127.0.0.1/myPathWork/index.php';

##set client:
$client = new Google_Client();
$client->setApplicationName('myAppName');
$client->setClientId('myClientId');
$client->setClientSecret('myClientSecret');
$client->setRedirectUri($redirectUri);
$client->setAccessType('offline');
#important! scopes 
$client->setScopes(array(
                    'https://www.googleapis.com/auth/youtube', 
                    'https://www.googleapis.com/auth/youtubepartner',
                    'https://www.googleapis.com/auth/youtube.upload', 
                )); 

if(isset($_GET['code'])){

    if (strval($_SESSION['google']['state']) !== strval($_GET['state']))
      exit('The session state did not match.');

    $client->authenticate($_GET['code']);
    $_SESSION['google']['token'] = $client->getAccessToken();
    header('location:'. $redirectUri);  
}

if(isset($_SESSION['google']['token']))
    $client->setAccessToken($_SESSION['google']['token']); # este es el key

if ($client->getAccessToken()){
    try {
        #this is the work in action!
        $youtube = new Google_Service_YouTube($client);
        $client->setDefer(true);

        $snippet = new Google_Service_YouTube_VideoSnippet();
        $snippet->setTitle('My Video title');
        $snippet->setDescription('My Video Description');
        $snippet->setTags(array('video upload','youtube v3', 'etc..'));
        $snippet->setCategoryId(22); # view: https://developers.google.com/youtube/v3/docs/videoCategories/list

        $status = new Google_Service_YouTube_VideoStatus();
        $status->setPrivacyStatus('private'); #private, public, unlisted
        $video = new Google_Service_YouTube_Video();
        $video->setSnippet($snippet);
        $video->setStatus($status);
        $chunkSizeBytes = 1 * 1024 * 1024;
        $client->setDefer(true);
        $insertRequest = $youtube->videos->insert("status,snippet", $video);
        $media = new Google_Http_MediaFileUpload($client,$insertRequest,'video/*', null,true,$chunkSizeBytes);

        #file location:
        $media->setFileSize(filesize('/var/www/my/path/video.mp4'));

        #Read the media file and upload it chunk by chunk.
        $status = false;
        $handle = fopen('/var/www/my/path/video.mp4', 'rb');

        while (!$status && !feof($handle)){
          $chunk = fread($handle, $chunkSizeBytes);
          $status = $media->nextChunk($chunk);
          fclose($handle);

           if ($status->status['uploadStatus'] == 'uploaded')
              echo "ok, " . $status['snippet']['title'] . ' - '. $status['id'] . "<hr>";
           else
            echo "error: " . $status['snippet']['title'] . ' - ' . $status['id'] . "<hr>";

            #show more print_r($status['snippet']);
        }

      $client->setDefer(false);
      #end Work!  
    }
    catch (Google_ServiceException $e) {
      exit('Error:' . htmlspecialchars($e->getMessage()));
    }
    catch (Google_Exception $e) {
      exit('Error:' . htmlspecialchars($e->getMessage())); 
    }
    $_SESSION['google']['token'] = $client->getAccessToken();
}
else{
     #GET NEW TOKEN
    $state = mt_rand();
    $client->setState($state);
    $_SESSION['google']['state'] = $state;
    $authUrl = $client->createAuthUrl();    
    header('location:' . $authUrl);
}

这篇关于使用Youtube API v3和PHP上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆