使用Javascript的Youtube数据API:直接上传视频

时间:2018-05-18 09:03:31

标签: javascript youtube-data-api

感谢Youtube Data API文档,我可以使用Javascript(XMLHttpRequest)执行可恢复的视频上传。这是有据可查的。但是有一个Javascript函数(youtube.videos.insert)(在我个人的观点中)记录不佳。经过两天的互联网研究,我不得不在这里寻求帮助。

以下是代码示例

function defineRequest() {
if (!isAuthorized) {
  alert("You need to authorize the request to proceed.");
  return;
}

var file = document.querySelector('input[type=file]').files[0];
if (!file) {
    alert("You need to select a file to proceed.");
    return;
}

var reader = new FileReader();
reader.onloadend = function() {
    alert("file load completed");

    var data = reader.result;
    var fileStream = new Blob([new Uint8Array(data)], {type: 'application/octet-stream'});
    //var fileStream = new Blob([data], {type: 'application/octet-stream'});
    alert(fileStream.size);
    alert(fileStream.type);

    var request = gapi.client.youtube.videos.insert({
        media: {
            mimeType: 'application/octet-stream',
            body: fileStream
        },
        part: 'id,snippet,status',
        notifySubscribers: true,
        resource: {
            snippet: {
                categoryId: 22,
                title: $('#title').val(),
                description: $('#description').text(),
                tags: ['hello']
            },
            status: {
                privacyStatus: $('#privacy-status option:selected').text()
            }
        }
    });

    request.execute(function (response) {
        alert(JSON.stringify(response));
        console.log(JSON.stringify(response));

        if (response === false) {
            alert("cannot upload video");
            console.log("Cannot upload video");
            return;
        } else {
            if (response.code != 0) {
                alert("cannot upload video");
                console.log("Cannot upload video");
                return;
            }

            var result = response.result;
            alert(JSON.stringify(result));
            alert("upload completed");          
        }
    });
}
reader.readAsArrayBuffer(file);

}

这是我收到的错误400(mediaBodyRequired)。愿有人有一些线索吗?

{
"code":400,
"data":[{
        "domain":"youtube.video",
        "reason":"mediaBodyRequired",
        "message":"The request does not include the video content.",
        "locationType":"other",
        "location":"body"
    }],
"message":"The request does not include the video content.",
"error": {
    "code":400,
    "data":[{
        "domain":"youtube.video",
        "reason":"mediaBodyRequired",
        "message":"The request does not include the video content.",
        "locationType":"other",
        "location":"body"
    }],
    "message":"The request does not include the video content."
}

}

1 个答案:

答案 0 :(得分:0)

您是否阅读过the docs?它与你的代码看起来很不一样。