Google 驱动器 API 使用浏览器版本创建空 'Untitled' 文件

Google Drive API creates empty 'Untitled' file with browser version

我正在尝试使用 Google Drive API 的 'browser' 版本,它似乎主要遵循 Nodejs 语法。但是除了浏览器的第一个 hello world 示例之外,似乎没有很多示例。

现在我正在尝试创建一个文件夹,然后在该文件夹中创建一个简单的 JSON 配置文件作为概念证明。然而,当我 运行 这段代码时,我只在我的 Google 驱动器中得到一个标记为 'Untitled' 的空文件。

这是文件创建的片段,returns 成功。

        this.MEM.config = {
            categories : {},
            createdOn : Date.now()
        }

        let fileMetadata = {
            name : 'config.json',
            parents : [this.MEM.parent]
        }

        let media = {
            mimeType : 'application/json',
            body : JSON.stringify(this.MEM.config)
        }

        query = {
            resource: fileMetadata,
            media: media,
            fields: 'id'
        }

        console.log(query);

        try {
            res = await gapi.client.drive.files.create(query);
        } catch(err) {
            throw err;
        }

        console.log(res);

这个结果似乎没有产生任何错误:

{
  "result": {
    "id": "1OI0ttFr11UH1__XAlSnyUil5hpp6mScB"
  },
  "body": "{\n \"id\": \"1OI0ttFr11UH1__XAlSnyUil5hpp6mScB\"\n}\n",
  "headers": {
    "cache-control": "no-cache, no-store, max-age=0, must-revalidate",
    "content-encoding": "gzip",
    "content-length": "67",
    "content-type": "application/json; charset=UTF-8",
    "date": "Thu, 29 Apr 2021 20:26:13 GMT",
    "expires": "Mon, 01 Jan 1990 00:00:00 GMT",
    "pragma": "no-cache",
    "server": "GSE",
    "vary": "Origin, X-Origin"
  },
  "status": 200,
  "statusText": "OK"
} 

除了在我用字符串化 object 指定的文件夹中创建 'config.json' 文件外,我只是在我的 Google 驱动器的根目录中得到一个无标题文件。

Modification points:

  • In the current stage, it seems that when gapi.client.drive.files.create is used, the file content cannot be included. For example, when you use the following query by removing the file content. The file can be created using the values of fileMetadata. But, the file content is not included.

      query = {
          resource: fileMetadata,
          fields: 'id'
      }
    
  • When you want to create new file by including the file content, how about directly requesting to the endpoint for uploading the file?

When your script is modified, it becomes as follows.

修改后的脚本:

this.MEM.config = {
  categories : {},
  createdOn : Date.now()
}
let fileMetadata = {
  name : 'config.json',
  parents : [this.MEM.patent]
}
const form = new FormData();
form.append('metadata', new Blob([JSON.stringify(fileMetadata)], {type: 'application/json'}));
form.append('file', new Blob([JSON.stringify(this.MEM.config)], {type: 'application/json'}));
fetch('https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&fields=id', {
  method: 'POST',
  headers: new Headers({'Authorization': 'Bearer ' + gapi.auth.getToken().access_token}),
  body: form
})
.then((res) => res.json())
.then((res) => console.log(res));
  • In this case, the access token is retrieved with gapi.auth.getToken().access_token. From your question, I understood that your access token can be used for uploading the file.

注:

  • In this modification, the file and file metadata are uploaded with multipart/form-data. In this case, the maximum content size is 5 MB. Please be careful this.
  • When you want to upload the large file, please use the resumable upload. In this case, the Javascript library of ResumableUploadForGoogleDrive_js might be useful.

参考文献: