Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

google drive sdk - How to upload a simple file through JavaScript

I just want to use Google Drive SDK in order to upload a simple file to my drive using JavaScript. The file is already been stored on my computer, all just I want is that read that file and then upload it to my drive.

Thanks in advance.

like image 517
Mohammad Areeb Siddiqui Avatar asked May 31 '26 03:05

Mohammad Areeb Siddiqui


1 Answers

  • Here are explained all types of uploads you can do with Google Drive API.
  • My code does a multipart upload with a client-side request using v3 Google Drive API. You can do it server-side as well.
  • In the metadata object parents property can be used to upload file to a specific folder. It's not mandatory.
const fileToUpload = inputUpload.files[0];

var metadata = {
  name: fileToUpload.name,
  mimeType: fileToUpload.type
  //parents: ["folderID"]
};

var formData = new FormData();
formData.append( "metadata", new Blob( [JSON.stringify( metadata )], {type: "application/json"} ));
formData.append( "file", fileToUpload );

fetch( "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart", {
  method: "POST",
  headers: new Headers({ "Authorization": "Bearer " + gapi.auth.getToken().access_token }),
  body: formData
}).then( function( response ){
  return response.json();
}).then( function( value ){
  console.log( value );
});

In order to make work this code, you have to be been authorized with OAuth 2.0.

  • Here you can find an example of authentication and here a better explanation on authentication. Both links are from APIs documentation.

Anyway a similar question had been already answered.

like image 51
d3vmak Avatar answered Jun 02 '26 16:06

d3vmak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!