提问者:小点点

使用curl和api v3在Youtube上上传视频


我会上传一个视频使用YouTubeAPI v3在PHP中的curl,如下所述:https://developers.google.com/youtube/v3/docs/videos/insert

我有这个函数

function uploadVideo($file, $title, $description, $tags, $categoryId, $privacy)
{
    $token = getToken(); // Tested function to retrieve the correct AuthToken

    $video->snippet['title']         = $title;
    $video->snippet['description']   = $description;
    $video->snippet['categoryId']    = $categoryId;
    $video->snippet['tags']          = $tags; // array
    $video->snippet['privacyStatus'] = $privacy;
    $res = json_encode($video);

    $parms = array(
        'part'  => 'snippet',
        'file'  => '@'.$_SERVER['DOCUMENT_ROOT'].'/complete/path/to/'.$file
        'video' => $res
    );

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://www.googleapis.com/upload/youtube/v3/videos');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $parms);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '.$token['access_token']));
    $return = json_decode(curl_exec($ch));
    curl_close($ch);

    return $return;
}

但它返回这个

stdClass Object
(
    [error] => stdClass Object
        (
            [errors] => Array
                (
                    [0] => stdClass Object
                        (
                            [domain] => global
                            [reason] => badContent
                            [message] => Unsupported content with type: application/octet-stream
                        )

                )

            [code] => 400
            [message] => Unsupported content with type: application/octet-stream
        )

)

该文件是一个MP4文件。

有人能帮忙吗?


共3个答案

匿名用户

更新版本:现在有了自定义上传网址和发送元数据的上传过程。整个过程需要2个请求:

>

  • 获取自定义上传位置

    首先,发出上传url的POST请求,发送至:

    "https://www.googleapis.com/upload/youtube/v3/videos"
    

    您需要发送2个标题:

    "Authorization": "Bearer {YOUR_ACCESS_TOKEN}"
    "Content-type": "application/json"
    

    您需要发送3个参数:

    "uploadType": "resumable"
    "part": "snippet, status"
    "key": {YOUR_API_KEY}
    

    您需要在请求正文中发送视频的元数据:

        {
            "snippet": {
                "title": {VIDEO TITLE},
                "description": {VIDEO DESCRIPTION},
                "tags": [{TAGS LIST}],
                "categoryId": {YOUTUBE CATEGORY ID}
            },
            "status": {
                "privacyStatus": {"public", "unlisted" OR "private"}
            }
        }
    

    从这个请求中,您应该会得到一个在标题中带有“位置”字段的响应。

    发布到自定义位置以发送文件。

    对于上载,您需要1个标题:

    "Authorization": "Bearer {YOUR_ACCESS_TOKEN}"
    

    并将该文件作为数据/正文发送。

    如果你通读了他们的客户端是如何工作的,你会看到如果返回代码500, 502, 503或504的错误,他们建议重试。显然,您希望在重试和最大重试次数之间有一个等待期。它每次都在我的系统中工作,尽管我使用的是python

    此外,由于自定义上传位置此版本是上传恢复能力,虽然我还需要。

  • 匿名用户

    不幸的是,我们还没有从PHP上传YouTubeAPI v3的具体示例,但我的一般建议是:

    • 使用PHP客户端库而不是cURL
    • 您的代码基于这个为驱动API编写的示例。因为YouTube API v3与其他Google API共享一个通用的API基础设施,所以在不同的服务中,上传文件等操作的示例应该非常相似
    • 看看Python示例,了解需要在YouTube v3上传中设置的特定元数据

    总的来说,您的cURL代码有很多不正确的地方,我无法完成修复它所需的所有步骤,因为我认为使用PHP客户端库是一个更好的选择。如果你确信你想使用cURL,那么我会听从其他人的意见来提供具体的指导。

    匿名用户

    python脚本:

    # categoryId is '1' for Film & Animation
    # to fetch all categories: https://www.googleapis.com/youtube/v3/videoCategories?part=snippet&regionCode={2 chars region code}&key={app key}
    meta =  {'snippet': {'categoryId': '1',
      'description': description,
      'tags': ['any tag'],
      'title': your_title},
      'status': {'privacyStatus': 'private' if private else 'public'}}
    
    param = {'key': {GOOGLE_API_KEY},
             'part': 'snippet,status',
             'uploadType': 'resumable'}
    
    headers =  {'Authorization': 'Bearer {}'.format(token),
               'Content-type': 'application/json'}
    
    #get location url
    retries = 0
    retries_count = 1
    while retries <= retries_count: 
        requset = requests.request('POST', 'https://www.googleapis.com/upload/youtube/v3/videos',headers=headers,params=param,data=json.dumps(meta))
        if requset.status_code in [500,503]:
            retries += 1
        break
    
    if requset.status_code != 200:
        #do something
    
    location = requset.headers['location']
    
    file_data = open(file_name, 'rb').read()
    
    headers =  {'Authorization': 'Bearer {}'.format(token)}
    
    #upload your video
    retries = 0
    retries_count = 1
    while retries <= retries_count:
        requset = requests.request('POST', location,headers=headers,data=file_data)
        if requset.status_code in [500,503]:
            retries += 1
        break
    
    if requset.status_code != 200:
        #do something
    
    # get youtube id
    cont = json.loads(requset.content)            
    youtube_id = cont['id']