本文介绍了YouTube API v3 over HTTP POST:上传视频时无法设置摘要(标题最终为“未知”)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试允许用户从我的网站上传YouTube视频,但我没有使用Javascript API,因为用户需要能够将内容上传到我的频道,而不是使用他们自己的帐户,我不能弄清楚如何使用JS API。

I am trying to allow users to upload YouTube videos from my website, but am not using the Javascript API, as users need to be able to upload content to my channel, rather than using their own accounts, and I couldn't figure out how to do that with the JS API.

无论如何,最终结果是我有一个HTML元素发布视频。视频上传,但最终标题为未知,没有描述等。不确定我做错了什么。以下是HTTP POST的有效负载(如 multipart / form-data ),它将被发送到:

Anyway, the end result is that I have an HTML element posting the video. The video gets uploaded, but ends up with title "unknown" and no description, etc. Not sure what I am doing wrong. Here is the payload of the HTTP POST (as multipart/form-data) that's getting sent to https://www.googleapis.com/upload/youtube/v3/videos?part=snippet,status&access_token=[accesstoken] :

------WebKitFormBoundaryqKACn63lpjqwi0sA
Content-Disposition: form-data; name="status[privacyStatus]"

unlisted
------WebKitFormBoundaryqKACn63lpjqwi0sA
Content-Disposition: form-data; name="snippet[title]"

Test Video Title
------WebKitFormBoundaryqKACn63lpjqwi0sA
Content-Disposition: form-data; name="snippet[description]"

Test video description
------WebKitFormBoundaryqKACn63lpjqwi0sA
Content-Disposition: form-data; name="videoFile"; filename="test_vide_upload.mp4"
Content-Type: video/mp4


------WebKitFormBoundaryqKACn63lpjqwi0sA--

我假设代码段状态的表单名称字段是错误的,但我尝试了各种选项,无法获得任何工作。我还尝试使用JSON编码的值 {snippet发送单个表单字段 data :{description:测试视频说明, title:测试视频标题},状态:{privacyStatus:unlisted}} 但这也不起作用。

I am assuming that the form names for snippet and status fields are wrong, but I've tried various options and can't get anything to work. I also tried sending a single form field data with the JSON-encoded value {"snippet":{"description":"Test video description","title":"Test Video Title"},"status":{"privacyStatus":"unlisted"}} but that did not work either.

我总是从API获得成功的JSON响应,包含片段和状态,并且视频已上传,但片段和状态尚未设置,它们是空值或默认值。任何线索?

I do always get a successful JSON response from the API, with the snippet, and status, and the video is uploaded, but the snippet and status have not been set, they are either empty or default values. Any clues?

推荐答案

我最终只能通过2个API调用来完成这项工作 - 一个用于上传视频(作为 multipart / form-data POST)并获取结果ID,第二次按该ID更新视频(作为应用程序/ json PUT,主体中带有片段

I was able to get this work in the end only by making 2 API calls - one to upload the video (as a multipart/form-data POST) and getting the resulting ID, and a second to update the video by that ID (as an application/json PUT with snippet in the body).

我从一个HTML表单开始像这样:

I started with an HTML form like this:

<form id="upload-yt-video" action="https://www.googleapis.com/upload/youtube/v3/videos?part=snippet&access_token=YOUR_TOKEN_HERE" method="post" enctype="multipart/form-data">
    <input type="text" name="title" placeholder="Video title">
    <textarea name="description" placeholder="Video description"></textarea>
    <input type="file" accept="video/*" name="videoFile">
    <input type="submit" value="Upload Video">
</form>

该表单单独上传视频,然后在JS中您可以捕获表单提交结果获取视频ID,然后在纯JS中进行第二次AJAX调用以更新它:

That form uploads the video all on its own, and then in JS you can capture the form submission result to get the video ID, then make a second AJAX call in pure JS to update it:

var YOUTUBE_API_TOKEN = 'YOUR_TOKEN_HERE';
var YOUTUBE_VID_CATEGORY_ID = 24; // "entertainment" as an example - note that a category ID is required
var YOUTUBE_VID_PRIVACY_STATUS = 'unlisted';

$('#upload-yt-video').ajaxForm({
  success: function(res, status) { 
    if (status !== 'success' || ! res.id) {
      console.error('problem uploading the video, response status:', status, 'response:', res);
      return;
    }

    console.log('form submission successful, video uploaded to youtube! response:', res);

    updateYouTubeVideo({
      id: res.id,
      token: YOUTUBE_API_TOKEN,
      title: $('#upload-yt-video [name=title]').val(),
      description: $('#upload-yt-video [name=description]').val()
    }, function(err, res) {
      if (err) {
        console.error('problem uploading the video - error while updating video attributes after upload:', err);
      }
      else {
        console.log('video updated! upload complete. response:', res);
      }
    });
  },
  error: function() {
    console.error('form submission failed', arguments);
  }
});

function updateYouTubeVideo(args, cb) {
  if (!args || !args.id || !args.token) {
    console.error('missing args: must at least include id and token');
    return;
  }

  var apiArgs = {
    id: args.id,
    snippet: {
      description: args.description || '',
      title: args.title || 'Video ' + new Date().toDateString(),
      categoryId: YOUTUBE_VID_CATEGORY_ID
    },
    status: {
      privacyStatus: YOUTUBE_VID_PRIVACY_STATUS
    }
  };

  $.ajax({
    type: 'PUT',
    url: 'https://www.googleapis.com/youtube/v3/videos?part=snippet,status',
    contentType: 'application/json',
    headers: {
        Authorization: 'Bearer ' + args.token
    },
    data: JSON.stringify(apiArgs),
    dataType: 'text',
    success: function(data) {
      if ($.type(data) === "string") data = JSON.parse(data);
      cb(null, data);
    },
    error: function(request, err){
      cb(err);
    }
  });
}

注意#1 - 这使用捕获初始表单提交。

免责声明#1 - 我从我已经不再存在的代码库中调整了这个,所以我无法测试它,所以这里可能会有一些小的错别字或错误。

免责声明#2 - 这在2014年9月有效 - 从那时起API可能已经有了更新!

Note #1 - this uses this jQuery plugin to capture the initial form submit.
Disclaimer #1 - I adapted this from a codebase I have that's no longer live, so I wasn't able to test it, so there may be minor typos or bugs in here.
Disclaimer #2 - This worked in September 2014 - there may have been updates to the API since then!

这篇关于YouTube API v3 over HTTP POST:上传视频时无法设置摘要(标题最终为“未知”)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 04:44