Home > Software design >  Uploading file via Google Drive API with simple upload (uploadType=media)
Uploading file via Google Drive API with simple upload (uploadType=media)

Time:10-14

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 onl oadFile = 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.

CodePudding user response:

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

  • Related