我正在尝试从单页应用程序使用CORS来对抗Youtube API。重点是避免整页重新加载(如http://gdata-samples.googlecode.com/svn/trunk/gdata/youtube_upload_cors.html正在做的那样)。通常有两种方法可以做到:
或
后者最优雅,但在某些劣质浏览器中不受支持。我处于幸运的位置,我可能会忽略这些浏览器。
现在我写了以下代码:
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在那里我非常好奇。
你有这样的工作吗?
答案 0 :(得分: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);