How to Delete Files Stored in Google Drive using Google Drive API V3 in Javascript

How to Delete Files Stored in Google Drive using Google Drive API V3 in Javascript

Welcome Folks I am back with another blog post. In this Post we will make a simple application which will allow you to delete the files stored in your Google Drive using the Google Drive API V3 in Javascript. Google Drive is one of the most popular medium of storing your data in the modern world. For this application we first of all need to create a project in Google Developers Console and get your client id and client secret. This process is illustrated in the next steps in a detailed fashion.

 

 

 

 

So just create a new project by providing a certain name or you can select from the created projects.

 

 

After selecting the project just click on create credentials and create a brand new OAuth Client ID.

 

 

Just select the option of web application because we are creating a web application which interacts with the Google Drive API.

 

 

So in this just provide localhost for the first field and the second field is important it needs to be the same for your project you can have different redirect url. It is basically the url to which Google redirects you whenever the user grants access to your application. Select it cautiously it needs to be same for your project.

 

Click on the create button to generate the client id and client secret. It will be different for you and don’t share this with others. Just copy both and store it somewhere we will be using it later in the application.

 

Click on the create button to generate the client id and client secret. It will be different for you and don’t share this with others. Just copy both and store it somewhere we will be using it later in the application.

READ  Complete Node.js Express MongoDB CRUD Project with Validation

 

 

After that create your project and inside your project create a brand new index.html file which will hold a simple button. For this project we are using XAMMP for local server.

 

 

<?php
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Delete Google Drive Files</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="main.js"></script>
</head>
<body>
   <div>
       <button id="login">
           Delete Drive Files
       </button>
   </div> 
</body>
</html>
?>

 

 

After that create a new file main.js which will hold the logic for index.html. In this file we will redirect the user to the permissions page where users can grant access to your application.

 

$(document).ready(function(){
     
     // client id of the project

     var clientId = "";

     // redirect_uri of the project

     var redirect_uri = "";

     // scope of the project

     var scope = "https://www.googleapis.com/auth/drive";

     // the url to which the user is redirected to

     var url = "";


     // this is event click listener for the button

     $("#login").click(function(){

        // this is the method which will be invoked it takes four parameters

        signIn(clientId,redirect_uri,scope,url);

     });

     function signIn(clientId,redirect_uri,scope,url){
      
        // the actual url to which the user is redirected to 

        url = "https://accounts.google.com/o/oauth2/v2/auth?redirect_uri="+redirect_uri
        +"&prompt=consent&response_type=code&client_id="+clientId+"&scope="+scope
        +"&access_type=offline";

        // this line makes the user redirected to the url

        window.location = url;




     }



});

 

The whole source code is full of comments and it is self explanatory we are using jQuery and also just replace the client id , redirect_uri with your values respectively. When you save this and execute this you will getting this output as shown below.

 

 

As you can see that whenever you execute this you will be redirected to the screen where you want to select your google account from this list of accounts and after that it grants access to your account by allowing this you will be granting access to this application. If you redirect_uri is different from the one you have mentioned in the Google Developers Console. You will getting this error of redirect_uri.

READ  Build a Webcam Filter Picture App with Webrtc & Canvas

 

 

After that create a brand new file called as download.php which will be the actual redirect_uri to which the user will land after allowing access to the application. Just create a new file download.php and copy paste the code.

 

<?php
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Delete Google Drive Files using Google Drive API V3 in Javascript</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
    <script src="download.js"></script>
    <style>
    .container{
        margin:0 auto;
        text-align:center;
    }
    #result{
        display:inline-block;
        text-align:center;
    }
    </style>
</head>
<body>
   <div class="container">
        <h2 style="text-align:center;">Delete Google Drive Files</h2>
        <div id="result">
            
        </div>
        <button id="delete">Delete</button>
   </div>
</body>
</html>
?>

 

 

You can see that there is a heading of Delete Google Drive Files and a button to do it

 

Just create a new download.js file to create the logic whenever the delete button is clicked from the user. First of all we will exchange the authorization code which is generated in the previous step with the access token. Access token are generally the medium from which we will making the requests to the API.

 

$(document).ready(function(){
    

    const urlParams = new URLSearchParams(window.location.search);
    var i;
    var j;
    var p2 = new Array();
    var button = new Array();
    var id="";
    const code = urlParams.get('code');
    const redirect_uri = "http://localhost/DriveDownload/download.php" // replace with your redirect_uri;
    const client_secret = "UbfLdbCd2QvFApooC7pjBWcr"; // replace with your client secret
    const scope = "https://www.googleapis.com/auth/drive";
    var access_token= "";
    var client_id = "844101305622-nnro5bh0a6b22079p1uu6qnvnbqiphgu.apps.googleusercontent.com"// replace it with your client id;
    

    $.ajax({
        type: 'POST',
        url: "https://www.googleapis.com/oauth2/v4/token",
        data: {code:code
            ,redirect_uri:redirect_uri,
            client_secret:client_secret,
        client_id:client_id,
        scope:scope,
        grant_type:"authorization_code"},
        dataType: "json",
        success: function(resultData) {
           
            
           localStorage.setItem("accessToken",resultData.access_token);
           console.log(localStorage.getItem("accessToken"));
           localStorage.setItem("refreshToken",resultData.refreshToken);
           localStorage.setItem("expires_in",resultData.expires_in);
           window.history.pushState({}, document.title, "/DriveDownload/" + "download.php");
           
           
           
           
        }
    });

    $("#delete").click(function(){
        listFiles();
    })


    function listFiles(){
        $.ajax({
            type:'GET',
            beforeSend: function (jqXHR, settings) {
                jqXHR.setRequestHeader('Authorization', 'Bearer '+ localStorage.getItem('accessToken'));
            },
            url:'https://www.googleapis.com/drive/v3/files',
            success:function(data){
                console.log(data);
                var length = data.files.length;
                console.log(data.files[0].id);
                for(i=0;i<length;i++)
                {
                    p2[i] = document.createElement('p');
                    button[i]=document.createElement('button');
                    button[i].innerHTML="Delete";
                    p2[i].innerHTML=data.files[i].name;
                    $(button[i]).attr("id",data.files[i].id);
                    $("body").append(p2[i]);
                    $("body").append(button[i]);
                    $(button[i]).click(function(event){
                        var element = event.target;
                        var id = element.id;
                        var retVal = confirm("Do you want to continue ?");
                        if( retVal == true ) {
                            deleteFileById(id);
                        } else {
                            
                        }
                    })
                }

                
            },
            error: function(data) {
                console.log(data); //or whatever
            }
        })
    }

    function deleteFileById(id){
        $.ajax({
            method:'DELETE',
            beforeSend: function (jqXHR, settings) {
                jqXHR.setRequestHeader('Authorization', 'Bearer '+ localStorage.getItem('accessToken'));
            },
            url:'https://www.googleapis.com/drive/v3/files/'+id,
            success:function(data){
                console.log(data);
                   alert("File Deleted");
                   $("body").empty();
                   listFiles();
        

            },
            error:function(error){
                console.log(error);
            }

        })
    }

});

 

READ  BootBoxJS - Bootstrap Modals Library For Creating Beautiful Bootstrap Modals

 

 

 

 

 

 

 

 

 

 

 

As you can see wheneer we hit the delete button for the following file a confirm dialog is presented to us taking the confirmation if we want to delete the file so whenever we press the ok button then it shows the file is deleted and then it also shows us the updated list of files coming from the API of Google Drive. In this we have successfully deleted the files stored in the Google Drive using the Google Drive API V3 in Javascript

 

Congratulations we are done Deleting files Stored in Google Drive using the Google Drive REST API V3 in Javascript from scratch. Thanks for reading this post and if you like reading this and wants to read more of this please subscribe the blog below to get all the notications.

Leave a Reply

Close Menu

Indian Desi Tools - Ultimate Tools Website

Demo Description


This will close in 20 seconds