我可以在Google云端硬盘上下载文本文件的元数据,但是无法通过XMLHttpRequest(XMLHttpRequest.status = 0)访问webContentLink。使用相同的webContentLink url的window.open(url)调用可以正常工作。似乎未为webContentLink启用CORS。
var clientId = '00000000000000';
var apiKey = 'AAAAAAAAAAAAAAAAAA';
var scopes = 'https://www.googleapis.com/auth/drive';
function loadDoc(url) {
//window.open(url);
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function() {
alert("readyState = " + xmlhttp.readyState + " status = " + xmlhttp.status);
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//... do something
}
}
xmlhttp.open("GET", url, true);
var myToken = gapi.auth.getToken();
xmlhttp.setRequestHeader("Referer", "http://mydomain");
xmlhttp.setRequestHeader("Accept", "text/x-tex");
xmlhttp.setRequestHeader("Content-Type", "text/x-tex");
xmlhttp.responseType = 'arraybuffer';
xmlhttp.overrideMimeType("text/plain");
xmlhttp.setRequestHeader('Authorization', 'Bearer ' + myToken.access_token);
xmlhttp.send();
}
function loadMetaData(url) {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var metaData = xmlhttp.responseText;
var index = metaData.search('"webContentLink"');
if (index != -1) {
var i1 = metaData.indexOf('"', index + 17);
var i2 = metaData.indexOf('"', i1 + 1);
var fileName = metaData.slice(i1 + 1, i2);
loadDoc(fileName);
}
}
}
xmlhttp.open("GET", url, true);
var myToken = gapi.auth.getToken();
xmlhttp.setRequestHeader('Authorization', 'Bearer ' + myToken.access_token);
xmlhttp.send();
}
// A simple callback implementation.
function pickerCallback(data) {
if (data.action == google.picker.Action.PICKED) {
var fileId = data.docs[0].id;
var url = 'https://www.googleapis.com/drive/v2/files/' + fileId;
loadMetaData(url);
}
}
因此,loadMetaData(url)函数可以正常工作,而loadDoc(url)函数则不能。我是对的,这是由于未为webContentLink设置CORS造成的,将来是否有可能对此进行更改?
谢谢,
丹尼
最佳答案
如果通过XHR下载文件,则应该改用downloadUrl
,并像以前一样提供访问 token 作为Authorization
header 。webContentLink
仅支持cookie身份验证,并且从XHR检索时可能失败。