Modern-day developers use Google API and other resources to create web applications. Developers using API to upload a file with JavaScript are far ahead of their competitors that don’t use it.
Knowing how to use JavaScript file upload API helps you create better applications.
Developers use the JavaScript file upload API to increase the storage memory of their applications. Before we continue in this article, we need to understand some basics.
- What is a Google Drive API and why is it used?
- How to use Google Drive API to upload a file with JavaScript?
- 1. Enable and Grant Authorization to the App
- 2. User Authentication Codes
- 3. Start the Client Function
- 4. Get the Details of the Users
- 5. Upload Files In JavaScript Using Google Drive API
What is a Google Drive API and why is it used?
A Google Drive API is a platform that makes connection possible to Google cloud storage. Google Drive API supports programming languages like Python and JavaScript. Developers can use it to create multiple apps with additional available storage.
Google Drive APIs help people use cloud storage to maximum capacity. Developers create apps that merge Google Drive, which gives compelling functionality to their applications. Reasons why developers use Google Drive API to upload a file with JavaScript include;
- Organizations can download and upload files with Google Drive
- You can easily share files and folders through Google Drive API easily
- Developers can create external links that access data from outside the drive
How to use Google Drive API to upload a file with JavaScript?
Developers can use Google Drive API with JavaScript file uploads, like Angular JS file upload and React JS file upload. You can use the following steps for the Google Drive API for the java file up loader.
1. Enable and Grant Authorization to the App
The first step for you to follow is to grant your app access with the following methods:
- Create an API key with the credentials and Oauth Client Id
- Specify websites for receiving requests to avoid CORS (Cross-Origin Resource Sharing) problems
- Specify your local host with the code; local host:<PORT> and don’t use IP
You will have your API_KEY and Client_ID when you do this step.
2. User Authentication Codes
Developers should write user authentication codes to specify additional scripts. Make sure you use Oauth 2.0 for this process because that is the only industry-standard protocol that Google permits.
When writing codes for authentication, specify some script to allow you to use window gapi client. After that, add a script to the component Did Mount (). Function with the following codes:
componentDidMount(){ var script = document.createElement(‘script’); script.onload=this.handleClientLoad; script.src=”https://apis.google.com/js/api.js”; document.body.appendChild(script); } |
Then allow the handle Client Load to load the gapi.client for you, and specify init client to start the gap.client for the call-back. Calling the gapi.client.init helps you define fields, which are as follows:
Api_Key And Client_ID
You can specify the authorization of your application’s certificate through these elements.
Scope
Scope helps developers specify lists that tally with the application materials they create for users, especially in React JS upload files.
You can use https://www.googleapis.com/discovery/v1/apis/drive/v3/rest as a scope for this process, and write the following codes:
var SCOPE = ‘https://www.googleapis.com/auth/drive.file’; var discoveryUrl = ‘https://www.googleapis.com/discovery/v1/apis/drive/v3/rest’; |
You can now define the init client function with the following codes:
initClient = () => { try{ window.gapi.client.init({ ‘apiKey’: “<YOUR API KEY>”, ‘clientId’: “<YOUR CLIENT ID>”, ‘scope’: SCOPE, ‘discoveryDocs’: [discoveryUrl] }).then(() => { this.setState({ googleAuth: window.gapi.auth2.getAuthInstance() }) this.state.googleAuth.isSignedIn.listen(this.updateSigninStatus); document.getElementById(‘sign document.getElementById(‘signout-btn’).addEventListener(‘click’, this.signOutFunction); }); }catch(e){ console.log(e); } } |
3. Start the Client Function
The first thing you should do after the result of the above codes is to start the client function. After that, get an Auth instance to save in a state variable, Google Auth.
The update Sign in Status function alters the user status approval, so you should append functions to the signing buttons. Then specify the states with the following codes:
state = { name: ”, googleAuth: ” } |
The sign In Function triggers when users click the sign-in button with the following codes, making it available:
signInFunction =()=>{ this.state.googleAuth.signIn(); this.updateSigninStatus() } |
You can call the update Sign in Status( ) function after the state changes with the following codes:
signOutFunction =()=>{ this.state.googleAuth.signOut(); this.updateSigninStatus() } |
4. Get the Details of the Users
The next thing to do is write the following codes to get the details of the users:
updateSignStatus = async ()=>{ var user = this.state.googleAuth.currentUser.get(); if (user.wc == null){ this.setState({ name: ” }); } else{ var isAuthorized = user.hasGrantedScopes(SCOPE); if(isAuthorized){ this.setState({ name: user.Ot.Cd }); //we will put the code of the third step here } } } |
5. Upload Files In JavaScript Using Google Drive API
Developers can use different methods to upload files in React JS with Google Drive API. We will be using the multi-part form to create files and specify the metadata for this upload process.
The following ways are methods that you can follow to upload files:
Initiate a POST request to the method’s/upload URL by using the parameter of upload Type=multipart
You can use https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart) as the upload URL to start the POST request.
Start a body for the request and format the body that contains two sides
- Metadata: Add the metadata first and set the Content-Type header to application/JSON; char set=UTF-8. After that, add the file’s metadata in JSON format.
- Media: Add the media second and set any Content-Type header of any MIME. You can now add the file’s data to the part of the media.
Write the following codes to summarize the two sides and create metadata for the file:
var fileName=’mychat123′; var fileData=’this is a sample data’; var contentType=’text/plain’ var metadata = { ‘name’: fileName, ‘mimeType’: contentType }; |
After that, compile the whole codes for your Java file upload API through your App.js:
import React, { Component } from ‘react’; var SCOPE = ‘https://www.googleapis.com/auth/drive.file’; var discoveryUrl = ‘https://www.googleapis.com/discovery/v1/apis/drive/v3/rest’; class App extends Component { state = { name: ”, googleAuth: ” } componentDidMount(){ var script = document.createElement(‘script’); script.onload=this.handleClientLoad; script.src=”https://apis.google.com/js/api.js”; document.body.appendChild(script); } initClient = () => { try{ window.gapi.client.init({ ‘apiKey’: “”, ‘clientId’: “”, ‘scope’: SCOPE, ‘discoveryDocs’: [discoveryUrl] }).then(() => { this.setState({ googleAuth: window.gapi.auth2.getAuthInstance() }) this.state.googleAuth.isSignedIn.listen(this.updateSigninStatus); document.getElementById(‘signin-btn’).addEventListener(‘click’, this.signInFunction); document.getElementById(‘signout-btn’).addEventListener(‘click’, this.signOutFunction); }); }catch(e){ console.log(e); } } signInFunction =()=>{ this.state.googleAuth.signIn(); this.updateSigninStatus() } signOutFunction =()=>{ this.state.googleAuth.signOut(); this.updateSigninStatus() } updateSigninStatus = ()=> { this.setSigninStatus(); } setSigninStatus= async ()=>{ var user = this.state.googleAuth.currentUser.get(); console.log(user) if (user.wc == null){ this.setState({ name: ” }); } else{ var isAuthorized = user.hasGrantedScopes(SCOPE); if(isAuthorized){ this.setState({ name: user.Ot.Cd }); const boundary=’foo_bar_baz’ const delimiter = “\r\n–” + boundary + “\r\n”; const close_delim = “\r\n–” + boundary + “–“; var fileName=’mychat123′; var fileData=’this is a sample data’; var contentType=’text/plain’ var metadata = { ‘name’: fileName, ‘mimeType’: contentType }; var multipartRequestBody = delimiter + ‘Content-Type: application/json; charset=UTF-8\r\n\r\n’ + JSON.stringify(metadata) + delimiter + ‘Content-Type: ‘ + contentType + ‘\r\n\r\n’ + fileData+’\r\n’+ close_delim; console.log(multipartRequestBody); var request = window.gapi.client.request({ ‘path’: ‘https://www.googleapis.com/upload/drive/v3/files’, ‘method’: ‘POST’, ‘params’: {‘uploadType’: ‘multipart’}, ‘headers’: { ‘Content-Type’: ‘multipart/related; boundary=’ + boundary + ” }, ‘body’: multipartRequestBody}); request.execute(function(file) { console.log(file) }); } } } handleClientLoad = ()=>{ window.gapi.load(‘client:auth2’, this.initClient); } render() { return ( <div className=”App”> <div>UserName: <strong>{ this.state.name}</strong></div> <button id=”signin-btn”>Sign In</button> <button id=”signout-btn”>Sign Out</button> </div> ); } } export default App; |