3

我正在尝试从单页应用程序对 Youtube API 使用 CORS。关键是要避免重新加载整个页面(就像http://gdata-samples.googlecode.com/svn/trunk/gdata/youtube_upload_cors.html正在做的那样)。通常有两种方法可以做到这一点:

  • 使用隐藏的 iframe

或者

  • 将 XMLHttpRequest 与 FormData 一起使用

后者最优雅,但在一些劣质浏览器中不支持。我很幸运,我可能会忽略那些浏览器。

现在我写了以下代码:

    var fd = new FormData();
    fd.append('token', token);
    fd.append('file', element.files[0]);
    var xhr = new XMLHttpRequest();
    xhr.upload.addEventListener("progress", uploadProgress, false);
    xhr.addEventListener("load", uploadComplete, false);
    xhr.addEventListener("error", uploadError, false);
    xhr.addEventListener("abort", uploadAbort, false);
    xhr.open("POST", $scope.uploadData.uploadUrl + '?nexturl=' + $location.absUrl());
    xhr.send(fd);

这有效(例如,它上传整个文件,同时愉快地发出进度事件),但最后它出错了。我不确定我做错了什么,但我真的很想看到一个使用这种策略而不是整页刷新的示例。尤其是处理我很好奇的响应和 id。

你有这样的工作吗?

4

1 回答 1

2

可以使用Direct Uploading API v2和 FormData + XHR2。就像是:

var DEV_KEY = '<here application key: you can find at https://code.google.com/apis/youtube/dashboard/gwt/index.html>';
var ACCESS_TOKEN = '<here oAuth2 token>';
var TOKEN_TYPE = 'Bearer ';

// Helper method to set up all the required headers for making authorized calls to the YouTube API.
function generateYouTubeApiHeaders() {
    return {
      Authorization: TOKEN_TYPE + ACCESS_TOKEN,
      'GData-Version': 2,
      'X-GData-Key': 'key=' + DEV_KEY,
      'X-GData-Client': 'App',
      'Slug': Math.random().toString()
    };
} 
// Helper method to set up XML request for the video.
function generateXmlRequest(title, description, category, keywords) {
    return '<?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>';
}

// Create XHR and add event listeners
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadError, false);
xhr.addEventListener("abort", uploadAbort, false);

// Specify POST target
xhr.open("POST", 'https://uploads.gdata.youtube.com/feeds/api/users/default/uploads');

// Prepare form data
var fd = new FormData();

// The order of attachments is absolutely important
fd.append('xmlrequest', generateXmlRequest('Test', 'Video', 'Autos', 'dsdfsdf, sdsdf'));
fd.append('video', document.forms.uploadNewVideoForm.file.files[0]);

// Add authentication headers
var headers = generateYouTubeApiHeaders();
for(var header in headers) {
    xhr.setRequestHeader(header, headers[header]);
}

// Send request
xhr.send(fd);
于 2013-01-15T16:01:43.080 回答