duandeng2011 2013-07-04 00:56
浏览 74

我的zend应用程序无法在youtube上上传文件

I am using the following code to upload small and large videos on youtube. The code properly works on localhost but when I run it on server and upload the same videos, it uploads all the SMALL files but not the large files. Once upload is completed youtube shows following Error for files with large size: Failed (unable to convert video file)

<?php
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata_YouTube');
Zend_Loader::loadClass('Zend_Gdata_AuthSub');
Zend_Loader::loadClass('Zend_Gdata_App_Exception');
session_start();
$_SESSION['Key'] = 'My Developer Key';
?>
<html>
<head>
</head>
<body>
    <?php

    if (!isset($_SESSION['sessionToken']) && !isset($_GET['token']) ){
        echo '<a href="' . getAuthSubRequestUrl() . '">Login!</a>';
    } else if (!isset($_SESSION['sessionToken']) && isset($_GET['token'])) {
      $_SESSION['sessionToken'] = Zend_Gdata_AuthSub::getAuthSubSessionToken($_GET['token']);
    }
    if(isset($_SESSION['sessionToken']))
    {
       $yt = new Zend_Gdata_YouTube(getAuthSubHttpClient());
       $myVideoEntry = new Zend_Gdata_YouTube_VideoEntry();

       $filesource = $yt->newMediaFileSource('myvideo.mov');
       $filesource->setContentType('video/quicktime');
       $filesource->setSlug('myvideo.mov');

    $myVideoEntry->setMediaSource($filesource);

   $myVideoEntry->setVideoDescription('this is my test video');

        $myVideoEntry->setVideoCategory("Music");

        $myVideoEntry->setVideoTitle('this is videoo');

        $myVideoEntry->SetVideoTags('tag1');


    $uploadUrl ='http://uploads.gdata.youtube.com/feeds/users/default/uploads';

    try {
        $newEntry = $yt->insertEntry($myVideoEntry,
                                     $uploadUrl,
                                     'Zend_Gdata_YouTube_VideoEntry');
    } catch (Zend_Gdata_App_HttpException $httpException) {
        echo $httpException->getRawResponseBody();
    } catch (Zend_Gdata_App_Exception $e) {
        echo $e->getMessage();
    }
    }

    ?>
</body>
</html>
<?php

function getAuthSubRequestUrl()
{
    $next = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
    $scope = 'http://gdata.youtube.com';
    $secure = false;
    $session = true;
    return Zend_Gdata_AuthSub::getAuthSubTokenUri($next, $scope, $secure, $session);
}

function getAuthSubHttpClient()
{
    if (!isset($_SESSION['sessionToken']) && !isset($_GET['token']) ){
        echo '<a href="' . getAuthSubRequestUrl() . '">Login!</a>';
        return;
    } else if (!isset($_SESSION['sessionToken']) && isset($_GET['token'])) {
      $_SESSION['sessionToken'] = Zend_Gdata_AuthSub::getAuthSubSessionToken($_GET['token']);
    }

    $httpClient = Zend_Gdata_AuthSub::getHttpClient($_SESSION['sessionToken']);
    $httpClient->setHeaders('X-GData-Key', 'key='. $_SESSION['Key']);
    return $httpClient;
}

function updateAuthSubToken($singleUseToken)
{
    try {
        $sessionToken = Zend_Gdata_AuthSub::getAuthSubSessionToken($singleUseToken);
    } catch (Zend_Gdata_App_Exception $e) {
        print 'ERROR - Token upgrade for ' . $singleUseToken
            . ' failed : ' . $e->getMessage();
        return;
    }

    $_SESSION['sessionToken'] = $sessionToken;
    generateUrlInformation();
    header('Location: ' . $_SESSION['homeUrl']);
}
?>
  • 写回答

1条回答 默认 最新

  • dongming8867 2013-07-11 13:26
    关注

    Here is a complete PHP example to upload large files.

        <?php
    
    ### TITLE: Resumable Uploads
    ### DESCRIPTION: <p>The code sample below calls the API's <code>videos.insert</code> method to add a video to user's channel. The code also utilizes <code>Google_MediaFileUpload</code> class with the <code>resumable upload</code> parameter set to <code>true</code> to be able to to upload the video in chunks.</p>
    ### API_METHOD: youtube.videos.insert
    
    // Call set_include_path() as needed to point to your client library.
    require_once 'Google_Client.php';
    require_once 'contrib/Google_YouTubeService.php';
    session_start();
    
    /* You can acquire an OAuth 2 ID/secret pair from the API Access tab on the Google APIs Console
     <http://code.google.com/apis/console#access>
    For more information about using OAuth2 to access Google APIs, please visit:
    <https://developers.google.com/accounts/docs/OAuth2>
    Please ensure that you have enabled the YouTube Data API for your project. */
    $OAUTH2_CLIENT_ID = 'REPLACE_ME';
    $OAUTH2_CLIENT_SECRET = 'REPLACE_ME';
    
    $client = new Google_Client();
    $client->setClientId($OAUTH2_CLIENT_ID);
    $client->setClientSecret($OAUTH2_CLIENT_SECRET);
    $redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'],
        FILTER_SANITIZE_URL);
    $client->setRedirectUri($redirect);
    
    // YouTube object used to make all API requests.
    $youtube = new Google_YoutubeService($client);
    
    if (isset($_GET['code'])) {
      if (strval($_SESSION['state']) !== strval($_GET['state'])) {
        die('The session state did not match.');
      }
    
      $client->authenticate();
      $_SESSION['token'] = $client->getAccessToken();
      header('Location: ' . $redirect);
    }
    
    if (isset($_SESSION['token'])) {
      $client->setAccessToken($_SESSION['token']);
    }
    
    // Check if access token successfully acquired
    if ($client->getAccessToken()) {
      try{
        // REPLACE with the path to your file that you want to upload
        $videoPath = "/path/to/file.mp4";
    
        // Create a snipet with title, description, tags and category id
        $snippet = new Google_VideoSnippet();
        $snippet->setTitle("Test title");
        $snippet->setDescription("Test description");
        $snippet->setTags(array("tag1", "tag2"));
    
        // Numeric video category. See
        // https://developers.google.com/youtube/v3/docs/videoCategories/list 
        $snippet->setCategoryId("22");
    
        // Create a video status with privacy status. Options are "public", "private" and "unlisted".
        $status = new Google_VideoStatus();
        $status->privacyStatus = "public";
    
        // Create a YouTube video with snippet and status
        $video = new Google_Video();
        $video->setSnippet($snippet);
        $video->setStatus($status);
    
        // Size of each chunk of data in bytes. Setting it higher leads faster upload (less chunks,
        // for reliable connections). Setting it lower leads better recovery (fine-grained chunks)
        $chunkSizeBytes = 1 * 1024 * 1024;
    
        // Create a MediaFileUpload with resumable uploads
        $media = new Google_MediaFileUpload('video/*', null, true, $chunkSizeBytes);
        $media->setFileSize(filesize($videoPath));
    
        // Create a video insert request
        $insertResponse = $youtube->videos->insert("status,snippet", $video,
            array('mediaUpload' => $media));
    
        $uploadStatus = false;
    
        // Read file and upload chunk by chunk
        $handle = fopen($videoPath, "rb");
        while (!$uploadStatus && !feof($handle)) {
          $chunk = fread($handle, $chunkSizeBytes);
          $uploadStatus = $media->nextChunk($insertResponse, $chunk);
        }
    
        fclose($handle);
    
    
        $htmlBody .= "<h3>Video Uploaded</h3><ul>";
        $htmlBody .= sprintf('<li>%s (%s)</li>',
            $uploadStatus['snippet']['title'],
            $uploadStatus['id']);
    
        $htmlBody .= '</ul>';
    
      } catch (Google_ServiceException $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();
    } else {
      // If the user hasn't authorized the app, initiate the OAuth flow
      $state = mt_rand();
      $client->setState($state);
      $_SESSION['state'] = $state;
    
      $authUrl = $client->createAuthUrl();
      $htmlBody = <<<END
      <h3>Authorization Required</h3>
      <p>You need to <a href="$authUrl">authorize access</a> before proceeding.<p>
    END;
    }
    ?>
    
    <!doctype html>
    <html>
    <head>
    <title>Video Uploaded</title>
    </head>
    <body>
      <?=$htmlBody?>
    </body>
    </html>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题