1

I'm using google API and I want to download files from UI to my google drive.

As I found in google drive API documentation here, I want to use simple import.

For the moment I have such code for my onChange input event.

const onLoadFile = async (e: { target: { files: any } }) => {
  const fileData = e.target.files[0];

  //gapi request
  uploadFile(body);
  return null;
};

uploadFile:

const uploadFile = async (body: string) => {
  const result = await gapiRequest({
    path: `${ENDPOINT}/upload/drive/v3/files`,
    method: 'POST',
    body,
  });
  setUploadFileData(result);
};

gapiRequest:

const gapiRequest = async (options: gapi.client.RequestOptions): Promise<any> =>
  new Promise<any>((resolve, reject) =>
    gapi.client.request(options).execute((res) => {
        resolve(res);
        if (!res) {
        reject(res);
      }
  })
);

I need to know which request body I need to create for such a request.

1 Answer 1

1

The request body should consist of a form that contains both metadata and the file, like so:

const metadata = {
    "name": "yourFilename",
    "mimeType": "text/plain", // whatever is appropriate in your case
    "parents": ["folder id or 'root'"], // Google Drive folder id
};

const form = new FormData();
form.append('metadata', new Blob([JSON.stringify(metadata)], { type: 'application/json' }));
form.append('file', file); // file could be a blob or similar

You might also need to add an uploadType parameter to your path property. The multipart value works even for simple uploads.

See also here: https://stackoverflow.com/a/68595887/7821823

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.