javascript - 从 url 下载 Google Drive 文件并通过帖子发送到后端

标签 javascript php google-api google-drive-api

我正在尝试从 javascript 中的 url(chrome 驱动文件)下载文件;并想将其发送到我的后端(php - laravel)。

var url = file.downloadUrl !== undefined ? file.webContentLink : file.exportLinks['application/pdf'];

console.log(url) // if I go to url, it downloads the file

if (url !== undefined) {
      var remote = new XMLHttpRequest();
      remote.open('GET', url);
      remote.setRequestHeader('Authorization', 'Bearer ' + gapi.client.getToken().access_token);
      remote.setRequestHeader('Access-Control-Allow-Origin', '*');
      remote.onload = function(e) {
          vm.handle_download(remote.responseText, file, 200); // do something with the fetched content;
      };
      remote.onerror = function(e) {
             vm.handle_download('error response', null, remote.statusText);
      };
      remote.send();
} else vm.handle_download('no downloadable url', {
     file: null,
     status: 'error'
});

和 handle 上

handle_download: function (content, file, status) {
        if (status !== 200) {
            console.log('error occured on status')
            return;
        }
}

Failed to load https://drive.google.com/uc?id=1D12321ofd4CNG-m9_Mp4aiDcnibNf&export=download: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://test.dev' is therefore not allowed access.

最佳答案

这是由于 same origin policy 造成的预期行为在网络中。由于您这样做是为了测试目的,请尝试此 Allow-Control-Allow-Origin Chrome 扩展。

您可以在 Using CORS tutorial 中阅读有关如何实现此功能的更多信息。 。 这个SO post还可能提供额外的见解。

关于javascript - 从 url 下载 Google Drive 文件并通过帖子发送到后端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47511071/

相关文章:

google-apps-script - 如何在 Google Apps 脚本中处理 Google Contacts API 返回的照片字节

java - Google 登录身份验证不起作用

javascript - 如何根据我的 jinja for 循环创建多个动态选择器?

javascript - Ruby 生成的 javascript 文件不会在页面刷新时更新

php - Symfony 在 "make"命名空间中没有定义命令

php - Mailchimp API 3.0 错误 : "Schema describes object, array found instead" is the code or on mailchimp's end?

php - 更改 http header 信息以隐藏服务器信息

http - 在 REST URI 中包含 @me 这样的标记不会破坏 HTTP 缓存吗?

javascript - JS选择这个具有特定类的 child

javascript - 如何使用 jquery 获取当前数据属性值?