javascript - Google Drive Rest API

标签 javascript google-drive-api

我遇到了 google drive rest api 的问题。我有一个按钮,当用户点击时,我从后端获得一个 blob excel 文件并将该文件上传到谷歌驱动器。该文件正在上传到谷歌驱动器,但当我打开它时,它显示“[object blob]”。实际内容不在文件中。这是我创建文件的功能。我从这里找到了这个解决方案:Create File with Google Drive Api v3 (javascript)

       var UploadExcelFile = function(name, data, callback){

        const boundary = '-------314159265358979323846';
        const delimiter = "\r\n--" + boundary + "\r\n";
        const close_delim = "\r\n--" + boundary + "--";

        const contentType = "application/vnd.google-apps.spreadsheet";

        var metadata = {
            'name': name,
            'mimeType': contentType
            };

            var multipartRequestBody =
                delimiter +
                'Content-Type: application/json\r\n\r\n' +
                JSON.stringify(metadata) +
                delimiter +
                'Content-Type: ' + contentType + '\r\n\r\n' +
                data +
                close_delim;

            var request = gapi.client.request({
                'path': '/upload/drive/v3/files',
                'method': 'POST',
                'params': {'uploadType': 'multipart'},
                'headers': {
                'Content-Type': 'multipart/related; boundary="' + boundary + '"'
                },
                'body': multipartRequestBody});
            if (!callback) {
            callback = function(file) {
                console.log(file)
            };
            }
            request.execute(callback);

      }```

```This is the response from the server:

  Response {type: "basic", url: 
  "http://localhost:54878/home/generateexcel", redirected: false, 
   status: 
   200, ok: true, …}
  body: ReadableStream
  locked: true
  __proto__: ReadableStream
  bodyUsed: true 
   headers: Headers
  __proto__: Headers
  ok: true
  redirected: false
  status: 200
  statusText: "OK"
  type: "basic"
  url: "http://localhost:54878/home/generateexcel"}

我从后端传入文件名和 blob excel 文件,如下所示:

 fetch('/home/generateexcel', {
                    method: 'POST',
                    body: JSON.stringify(postData),
                    headers: {
                        "Content-Type": "application/json"
                    },
                }).then(function (response) {
                    response.blob().then(function (result)
                        UploadExcelFile('newfile', result)
                    });
                }).catch(function (err) {
                    // Error :(
                });

最佳答案

  • 您想将下载的 xlsx 文件上传到 Google 云端硬盘。
  • 您已经确认可以下载 xlsx 文件。
  • 上传 xlsx 文件后,您想将其转换为 Google 电子表格。
  • 您可以使用 Drive API 和访问 token 来上传文件。

如果我的理解是正确的,这个修改怎么样?在此修改中,我使用 FormData() 来创建请求主体,并使用 fetch() 来请求 Drive API。我认为您的情况有几种解决方案。因此,请将其视为其中之一。

修改后的脚本:

我修改了 UploadExcelFile()。请修改如下,然后重试。

function UploadExcelFile(name, data) {
  var metadata = {
    name: name,
    mimeType: "application/vnd.google-apps.spreadsheet",
  };
  var form = new FormData();
  form.append('metadata', new Blob([JSON.stringify(metadata)], {type: 'application/json'}));
  form.append('file', data);
  fetch('https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&fields=id,name,kind', {
    method: 'POST',
    headers: new Headers({'Authorization': 'Bearer ' + gapi.auth.getToken().access_token}),
    body: form
  }).then((res) => {
    return res.json();
  }).then(function(val) {
    console.log(val);
  });
}

在我的环境中,我可以确认此脚本有效。但如果这在您的环境中不起作用,我深表歉意。

关于javascript - Google Drive Rest API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54697079/

相关文章:

javascript - 为什么这段代码中的 id 是 'undefined'?

javascript - SoundManager 2 360Ui安装

google-drive-api - 如何在一个请求中为多个用户添加对 Google Drive 文件的读取权限

oauth-2.0 - 是否需要按用户 API 发现(Google Drive SDK)?

ios - iOS 中的 Google Drive 集成以上传 PDF 文件

css - 当托管在 Google Drive 上时,Google Web Font 不会在 Chrome 中显示

javascript - 如何摆脱重叠的 svg 形状的细线

javascript - 如何在主导航中以不同方式设置当前页面的样式?

.net - Google云端硬盘-无法下载经过身份验证(OAuth2)请求的缩略图

javascript - 如何在一行中匹配 javascript 中的正则表达式