2

I'm trying to use the 'browser' version of the Google Drive API, which seems to mostly follow the Nodejs syntax. But there don't seem to be many examples outside of the first hello world example for the browser.

Right now I'm trying to create a folder, and then create a simple JSON config file inside that folder as a proof of concept. However when I run this code, I only get an empty file labeled 'Untitled' in my Google Drive.

Here's a snippet for the file creation, that returns successful.

        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);

The result of this doesn't seem to produce any errors:

{
  "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"
} 

Except, instead of creating a 'config.json' file in the folder I specified with the stringified object, I just get an Untitled file in the root of my Google Drive.

Benjamin Collins
  • 1,044
  • 2
  • 9
  • 23

1 Answers1

1

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.

Modified script:

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.

Note:

  • 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.

References:

Tanaike
  • 181,128
  • 11
  • 97
  • 165
  • Thank you! This worked. There's a 'config.json' file in the folder specified with the stringified content. It looks like this answer is a more elegant solution of this one: https://stackoverflow.com/questions/34905363/create-file-with-google-drive-api-v3-javascript/44527113?noredirect=1#answer-35182924. In both cases, it basically looks like gapi.drive.client.file.create so you have to send a request directly to the REST interface. – Benjamin Collins Apr 30 '21 at 05:35
  • 1
    @Benjamin Collins Thank you for replying. I'm glad your issue was resolved. Thank you, too. – Tanaike Apr 30 '21 at 12:11