在 this thread 的帮助下我想出了下面的代码。如何获取 Google Drive 文件 ID,打开文件的直接链接并获取流式传输超过 100 MB 的文件所需的病毒扫描确认 ID,然后拼凑链接?我有点卡在 xhr 部分了。
function fixGoogleDriveURL(url) {
if (url.indexOf('drive.google.com') !== -1) {
var DocIDfull = url;
var DocIDstart = DocIDfull.indexOf('open?id=');
if (DocIDstart == -1) {
// invalid
return url;
}
var DocID = DocIDfull.slice(DocIDstart+8);
url = 'https://drive.google.com/uc?export=download&id=' + DocID;
var xhr = new XMLHttpRequest();
xhr.onload = function () {
if (xhr.readyState === xhr.DONE) {
if (xhr.status === 200) {
var token = xhr.responseText.match("/confirm=([0-9A-Za-z]+)&/");
window.location.replace(url + '&confirm=' + token[1]);
// should I add url += '&confirm=' + token[1] here instead of window.location?
}
}
};
xhr.open("GET", url);
xhr.send();
}
return url;
}
console.log(fixGoogleDriveURL('https://drive.google.com/open?id=1C25uoL6nIqqNhex3wm8VwODsO2q2pXBt') + "\n<-- should output:\nhttps://drive.google.com/uc?export=download&id=1C25uoL6nIqqNhex3wm8VwODsO2q2pXBt&confirm=XXXXX");
最佳答案
Google 未明确允许使用客户端 JavaScript 抓取 GDrive,因此您的 Ajax 调用/XHR 失败。
绕过该限制的唯一方法是在中间使用代理,该代理将转发 Google 的网站代码,但添加适当的 Access-Control Allow-Origin Headers。 你可以为此使用你自己的服务器(一些最小的服务器端脚本代码就可以)或者你可以使用像 http://multiverso.me/AllOrigins/ 这样的服务。或 https://corsproxy.github.io/为您代理请求。
AllOrigins 站点有一些与 jQuery 一起使用的示例代码,但基本上它们是通过 URI 对您要访问的 URL 进行编码并将该字符串附加到站点的代理 URL 来工作的。
这是 freecodecamp.org 的一篇文章,概述了如何使用这些服务(跳到 不要让 CORS 阻止你!
部分。
注意:一个安全建议:这些服务目前运行良好,但明天它们可能会倒闭并开始提供恶意数据,或者将您的文件请求重定向到完全不同的文件或完全不同的网站。由您决定是否要信任这些陌生人。
关于javascript - 绕过 Google Drive 链接的病毒扫描并获取确认 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53026080/