我可以在 Google Drive 上下载文本文件的元数据,但我无法通过 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,将来是否有可能改变?
谢谢,丹尼