Mohammad Areeb Siddiqui
Mohammad Areeb Siddiqui

Reputation: 10189

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.

Upvotes: 3

Views: 5422

Answers (2)

d3vmak
d3vmak

Reputation: 83

  • 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.

Upvotes: 5

JunYoung Gwak
JunYoung Gwak

Reputation: 2987

Here is quickstart of javascript in official documentation which covers exactly what you want.

Upvotes: -3

Related Questions