Skip to content

WebNinjaDeveloper.com

Programming Tutorials




Menu
  • Home
  • Youtube Channel
  • Official Blog
  • Nearby Places Finder
  • Direction Route Finder
  • Distance & Time Calculator
Menu

Google Drive API Example to Download Files From URL Using OAuth2 in Browser Using Javascript

Posted on December 1, 2022

 

 

Welcome folks today in this blog post we will be looking on how we can download files stored in google drive from url and save it inside the computer in the browser. All the full source code of the application is shown below.

 

 

Get Started

 

 

In order to get started you need to read the below blog posts to get on the same page as I will start in this blog post. Before that I have shown successfully how to successfully login and logout using google OAuth2 in javascript. Read it first before beginning this one. Link is given as follows

 

 

Javascript OAuth2 Google Login & Logout Example Using Access Token in Browser

 

 

And after that you need to read the below blog post in which I have shown how to upload the file to google drive using the oauth2 authentication in browser using the google drive api in javascript. Link is given below

 

 

Javascript OAuth2 Google Drive Upload File to Folder Using Fetch API & HTTP POST Method in Browser

 

 

And also after that I have shown how basically you can search the files stored inside the google drive and display it inside html5 table and also we looked on how we can permanently delete files stored inside google drive. The link of the blog post is shown below

 

 

Javascript OAuth2 Google Drive API Example to Search Images & Videos & Delete Specific File in Browser

 

 

Now we will start this blog post. In this one we will be adding the functionality of downloading files stored in google drive using it’s webContentLink property in google drive get files method. For this one the directory structure will look something like this as shown below

 

 

 

 

Now first of all we need to modify the profile.html file and add the download button inside the table as shown below

 

 

profile.html

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
 
<body>
    <div class="container">
        <h1>Welcome to profile page</h1>
        <h2>Upload file to google drive</h2>
        <form id="form">
            <input type="file" id="file" required>
            <input type="submit" value="Upload File">
        </form>
        <button id="search">Search Files</button>
        <button id="images">Only Images</button>
        <button id="videos">Only Videos</button>
        <button id="pdf">Only PDF</button>
        <button id="logout">Logout</button>
        <table class="table table-striped">
            <thead>
                <tr>
                    <th>Name of File</th>
                    <th>Mimetype</th>
                    <th>Download File</th>
                    <th>Delete File</th>
                </tr>
            </thead>
            <tbody id="result">
 
            </tbody>
        </table>
    </div>
</body>
<script type="module" src="profile.js"></script>
 
</html>

 

 

Also as you can see guys we have also imported the bootstrap cdn and added the table class of bootstrap to the table html element. Now if you open the file inside the browser it will look something as shown below

 

 

 

 

Now we need to modify the profile.js code guys here we will be adding the property which will be webContentLink which will actually contain the download url for the google drive file. Here we will be using the same get method for searching the files from google drive but this time inside the fields parameter we need to add the webContentLink property as shown below

 

 

 

 

And now we will be adding the download button dynamically by manipulating the innerHTML property and inside it we will be containing the anchor element which will point to the webContentLink url and we can easily download the file as an attachment inside the browser. Now the full function of searchFiles() becomes like this

 

 

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
function searchFiles(q = "") {
  result.innerHTML = "";
  fetch(
    `https://www.googleapis.com/drive/v3/files?q=${q}&pageSize=5&supportsAllDrives=true&fields=files(name,id,mimeType,webContentLink)`,
    {
      method: "GET",
      headers: new Headers({ Authorization: "Bearer " + ACCESS_TOKEN }),
    }
  )
    .then((res) => {
      return res.json();
    })
    .then(function (val) {
      console.log(val);
      val.files.forEach((file) => {
        let id = file.id;
        result.innerHTML += `
            <tr>
                <td><a target="_blank" href="https://drive.google.com/file/d/${file.id}">${file.name}</a>
                </td>
                <td>${file.mimeType}</td>
                <td>
                    <a target="_blank" href="${file.webContentLink}">Download ${file.name}</a>
                </td>
                <td>
                <button onclick="
                fetch('https://www.googleapis.com/drive/v3/files/${id}',{
                    method:'DELETE',
                    headers:new Headers({Authorization:'Bearer ${ACCESS_TOKEN}'})
                })
                .then((info) => {
                    console.log(info)
                    alert('file is deleted')
                })
                ">Delete ${file.name}</button>
                </td>
            </tr>
            `;
      });
    });
}

 

 

And now if you open the web application you will be able to download the files as well as shown below

 

 

 

 

 

FULL SOURCE CODE

 

 

Recent Posts

  • Android Java Project to Download Multiple Images From URL With Progressbar & Save it inside Gallery
  • Android Java Project to Capture Image From Camera & Save it inside Gallery
  • Android Java Project to Crop,Scale & Rotate Images Selected From Gallery and Save it inside SD Card
  • Android Kotlin Project to Load Image From URL into ImageView Widget
  • Android Java Project to Make HTTP Call to JSONPlaceholder API and Display Data in RecyclerView Using GSON & Volley Library
  • Angular
  • Bunjs
  • C#
  • Deno
  • django
  • Electronjs
  • java
  • javascript
  • Koajs
  • kotlin
  • Laravel
  • meteorjs
  • Nestjs
  • Nextjs
  • Nodejs
  • PHP
  • Python
  • React
  • ReactNative
  • Svelte
  • Tutorials
  • Vuejs




©2023 WebNinjaDeveloper.com | Design: Newspaperly WordPress Theme