user2418670
user2418670

Reputation:

Google Drive Upload File

I had the upload file working with xmlhttprequest but I was using a Service Worker so I switched to using fetch.

I am getting a 401 error when sending my request but I know I have an access token.

function uploadFile() {
  let accessToken = gapi.auth.getToken().access_token; // Google Drive API Access Token

  let fileContent = document.querySelector('#content').value; // As a sample, upload a text file.
  console.log('File Should Contain : ' + fileContent);
  let file = new Blob([fileContent], { type: 'application/text' });

  let metadata = {
    name: 'Background', // Filename
    mimeType: 'text/plain', // mimeType at Google Drive
    parents: ['root'], // Folder ID in Google Drive
  };

  let form = new FormData();
  form.append(
    'metadata',
    new Blob([JSON.stringify(metadata)], { type: 'application/json' })
  );
  form.append('file', file);

  fetch(
    'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&fields=id',
    {
      method: 'POST',
      headers: new Headers({ Authorization: 'Bearer' + accessToken }),
      body: form,
    }
  )
    .then((res) => {
      return res.json();
    })
    .then(function (val) {
      console.log(val);
    });
}

Anyone know what I am missing ?

Here is the error I am receiving back

error:
code: 401
errors: Array(1)
0: {domain: "global", reason: "authError", message: "Invalid Credentials", locationType: "header", location: "Authorization"}
length: 1
__proto__: Array(0)
message: "Invalid Credentials"
__proto__: Object
__proto__: Object

Upvotes: 1

Views: 173

Answers (1)

Tanaike
Tanaike

Reputation: 201378

I think that the reason of your issue of Invalid Credentials is headers: new Headers({ Authorization: 'Bearer' + accessToken }),. Please modify as follows.

From:

headers: new Headers({ Authorization: 'Bearer' + accessToken }),

To:

headers: new Headers({ Authorization: 'Bearer ' + accessToken }),
  • Please add a space of before Bearer like above.
  • I think that when above modification is done, your script can upload the text file.

Reference:

Upvotes: 1

Related Questions