0

I am creating a part of a website where the user can design a certain picture. When they are done I want the picture to be sent to a company Google Drive. I do not have access to the backend of that website, therefore I need to make all this work just in JavaScript.

I set up the API key and OAuth in Google Developer Console. However, I can't find a good solution to make the authentication work. The gapi.auth.getToken() always returns 404. My code looks like this:

function initClient() {
  gapi.client
    .init({
      apiKey: API_KEY,
      clientId: CLIENT_ID,
      scope: "https://www.googleapis.com/auth/drive",
      discoveryDocs: [
        "'https://www.googleapis.com/discovery/v1/apis/drive/v3/rest'",
      ],
    })
    .then(function () {
      GoogleAuth = gapi.auth2.getAuthInstance();
      GoogleAuth.isSignedIn.listen(updateSigninStatus);
    });
}

function sendToDrive() {
  gapi.load("client:auth2", initClient);

  let file = canvas.toDataURL("image/png"); // file

  var metadata = {
    name: file.name,
    mimeType: file.type,
    parents: [FOLDER_ID],
  };
  var 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",
    {
      method: "POST",
      headers: new Headers({
        Authorization: "Bearer " + gapi.auth.getToken().access_token, // Returns 404
      }),
      body: form,
    }
  )
    .then((res) => {
      return res.json();
    })
    .then(function (val) {
      console.log(val);
    });
}

Not sure where to look now - the OAuth and API Key configuration seems right, the code returns 404 with no explanation ("gapi.client.error: Pa"), and I couldn't find this kind of use case in the docs (backend side is always used there).

Thanks in advance for any help!

Tomáš Zajda
  • 147
  • 1
  • 15
  • Are you sure it is the token that gives you the 404? I think it is rather the request itself. – ziganotschka Aug 02 '21 at 08:42
  • Have a look at https://stackoverflow.com/questions/17084643/getting-a-404-when-trying-to-upload-a-file-to-the-google-drive-api-suspecting-a , https://stackoverflow.com/questions/34905363/create-file-with-google-drive-api-v3-javascript/35182924#35182924 , https://stackoverflow.com/questions/52081706/google-drive-api-correct-way-to-upload-binary-files-via-the-multipart-api, https://stackoverflow.com/questions/50357074/gdrive-multipart-upload-jquery and https://stackoverflow.com/questions/32714662/how-to-send-an-http-multipart-post-request-with-a-blob-in-it – ziganotschka Aug 02 '21 at 08:42
  • And the [Google documentation](https://developers.google.com/drive/api/v3/manage-uploads#node.js). – ziganotschka Aug 02 '21 at 08:42

0 Answers0