使用Node.js上传视频到YouTube

9

我已经对官方Google API node客户端有了一些进展,但是我在想如何将视频文件上传到YouTube时遇到了一些困难。

我有一个视频:example.mp4

我有以下代码:

OAuth2Client = googleapis.OAuth2Client;               
var oauth2Client = new OAuth2Client('XXXXXX', 'XXXXXXX', 'http://callback_url');

googleapis.discover('youtube', 'v3').execute(function(err, client) {
  if (err) console.log(err);
  // I think the following is the bones of what I want to do
  client.youtube.videos.insert({}).execute(function(err, client) {
    if (err) console.log(err);
  }); 
});

我只在使用insert方法时得到了一个错误(我预期不传递参数会出现这种情况),客户端初始化并返回正常。

我不确定如何将视频(与脚本位于同一目录中)传递到YouTube。仅提供指针将非常感激。

3个回答

14

这段代码怎么样:

var googleapis = require('googleapis');

googleapis.discover('youtube', 'v3').execute(function(err, client) {

var metadata = {
    snippet: { title:'title', description: 'description'}, 
    status: { privacyStatus: 'private' }
};

client
    .youtube.videos.insert({ part: 'snippet,status'}, metadata)
    .withMedia('video/mp4', fs.readFileSync('user.flv'))
    .withAuthClient(auth)
    .execute(function(err, result) {
        if (err) console.log(err);
        else console.log(JSON.stringify(result, null, '  '));
    });
});

经过一些编辑,这个回答解决了我之前的疑问(“如何设置片段字段?”)。 - Frank Schwieterman
2
我遇到了一个错误 TypeError: youtube.videos.insert(...).withMedia is not a function...还有其他人也看到了吗? - Brad Orego

1

0

这段代码对我有效:

var file_reader = fs.createReadStream(file_path, {encoding: 'binary'});
var file_contents = '';
file_reader.on('data', function(data)
{
    file_contents += data;
});
file_reader.on('end', function()
{
    var xml =
        '<?xml version="1.0"?>' +
        '<entry xmlns="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" xmlns:yt="http://gdata.youtube.com/schemas/2007">' +
        '   <media:group>' + 
        '       <media:title type="plain">' + title + '</media:title>' +
        '       <media:description type="plain">' + description + '</media:description>' +
        '       <media:category scheme="http://gdata.youtube.com/schemas/2007/categories.cat">' + category + '</media:category>' +
        '       <media:keywords>' + keywords + '</media:keywords>' + 
        '   </media:group>' + 
        '</entry>';

    var boundary = Math.random();
    var post_data = [];
    var part = '';

    part = "--" + boundary + "\r\nContent-Type: application/atom+xml; charset=UTF-8\r\n\r\n" + xml + "\r\n";
    post_data.push(new Buffer(part, "utf8"));

    part = "--" + boundary + "\r\nContent-Type: video/mp4\r\nContent-Transfer-Encoding: binary\r\n\r\n";
    post_data.push(new Buffer(part, 'ascii'));
    post_data.push(new Buffer(file_contents, 'binary'));
    post_data.push(new Buffer("\r\n--" + boundary + "--"), 'ascii');

    var post_length = 0;
    for(var i = 0; i < post_data.length; i++)
    {
        post_length += post_data[i].length;
    }

    var options = {
      host: 'uploads.gdata.youtube.com',
      port: 80,
      path: '/feeds/api/users/default/uploads?alt=json',
      method: 'POST',
        headers: {
            'Authorization': 'GoogleLogin auth=' + auth_key,
            'GData-Version': '2',
            'X-GData-Key': 'key=' + exports.developer_key,
            'Slug': 'example.mp4',
            'Content-Type': 'multipart/related; boundary="' + boundary + '"',
            'Content-Length': post_length,
            'Connection': 'close'
        }
    }

    var req = http.request(options, function(res)
    {
        res.setEncoding('utf8');

        var response = '';
        res.on('data', function(chunk)
        {
            response += chunk;
        });
        res.on('end', function()
        {
            console.log(response);
            response = JSON.parse(response);

            callback(response);
        });
    });

    for (var i = 0; i < post_data.length; i++)
    {
        req.write(post_data[i]);
    }

    req.on('error', function(e) {
      console.error(e);
    });

    req.end();
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接