更新:这是GoogleDrive中的一个错误,CORS未启用上传URI。 @Nivco指示我使用Google的客户端库,它使用iframe和代理(而不是CORS)。我将(测试的)工作代码放在底部,并附有详细的解释。请参阅下面的示例中的答案。https://www.googleapis.com/upload/drive/v2/files是否真的支持CORS?
Inserting File to Google Drive through API和Authorization of Google Drive using JavaScript表示上传端点支持CORS,但我一直无法使用它们。我可以使用Files: insert获得授权并插入空文件,但我无法上传内容 - 当我使用https://www.googleapis.com/upload/drive/v2/files时,如果使用示例中给出的两种技术中的任何一种,我会得到405(方法不允许)错误在插入文件堆栈溢出文章中。
CORS是否可以用于v1并且尚未启用v2?
编辑:顺便说一句,405错误是在铬制作的选项请求。
编辑:下面是从我的尝试之一代码:
之前,我提出我想强调的是,我能够进行身份验证和列表文件的代码。我只是无法将数据上传到文件。
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart');
xhr.setRequestHeader('Authorization', 'Bearer ' + params.access_token);
xhr.setRequestHeader("Content-Type", 'multipart/related; boundary="END_OF_PART"');
xhr.onreadystatechange = function(data) {
if (xhr.readyState == DONE) {
document.getElementById("files").innerHTML = "Uploaded file: " + xhr.responseText;
};
}
xhr.send([
mimePart("END_OF_PART", "application/json", json),
mimePart("END_OF_PART", "text/plain", "a\nb\n"),
"\r\n--END_OF_PART--\r\n",
].join(''));
function mimePart(boundary, mimeType, content) {
return [
"\r\n--", boundary, "\r\n",
"Content-Type: ", mimeType, "\r\n",
"Content-Length: ", content.length, "\r\n",
"\r\n",
content,
].join('');
}
这里是要求:
Request URL:https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart
Request Method:OPTIONS
这里是回应:
Status Code:405 Method Not Allowed
cache-control:no-cache, no-store, must-revalidate
content-length:0
content-type:text/html; charset=UTF-8
date:Mon, 23 Jul 2012 22:41:29 GMT
expires:Fri, 01 Jan 1990 00:00:00 GMT
pragma:no-cache
server:HTTP Upload Server Built on Jul 17 2012 16:15:04 (1342566904)
status:405 Method Not Allowed
version:HTTP/1.1
没有反应,因为Chrome浏览405错误对于OPTIONS请求。没有发布,因为浏览器无法继续,因为它的OPTIONS请求有405失败了,所以它打印在控制台此错误:
XMLHttpRequest cannot load https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart. Origin https://leisurestorage.appspot.com is not allowed by Access-Control-Allow-Origin.
您是否使用特定的浏览器?我尝试过使用Chrome,它对我来说非常合适。你有没有看过[google-apis-javascript-client](http://code.google.com/p/google-api-javascript-client/wiki/CORS)项目页面? – Alain 2012-07-23 21:36:16
我试过Chrome和Firefox。我正在编辑我的原创以添加更多信息。 – 2012-07-23 22:32:23
我添加了更多信息。我可以使用该技术进行身份验证并获取文件列表,但我无法使用它将数据上传到文件。 – 2012-07-23 22:52:36