Firebase Storage Web JSP JavaScript: How to Delete Image

Abb Source

I am fairly new to using firebase and JavaScript. I have a JSP page which displays image from Firebase storage. I would like to know how to delete the displayed image. I have already had a look at several answers here on StackOverFlow and also on google but even after reading the answers I am not able understand how to delete the image. I know for sure that this is not a duplicate question here on stackoverflow.

I have tried using the code from

Firebase Delete Files on Web

But the moment I paste the code I get error on delete function stating, "Syntax error on token "delete", Identifier expected" and on catch stating, "Syntax error on token "catch", Identifier expected"

I am using a Confirm button onclick to call a javascript function i.e. showImgDetails().

My JSP is as follows:

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
  <%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
    <html>

    <head>
      <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
      <title>Add Event</title>
      <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">

      <!-- Favicon-->
      <link rel="shortcut icon" href="resources/images/favicon.ico" />
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

      <!-- mega menu -->
      <link href="resources/css/mega_menu.css" rel="stylesheet" type="text/css" />

      <!-- mega menu -->


      <!-- Flaticon -->
      <link href="resources/css/flaticon.css" rel="stylesheet" type="text/css" />

      <!-- General style -->
      <link href="resources/css/general.css" rel="stylesheet" type="text/css" />

      <!-- main style -->
      <link href="resources/css/style.css" rel="stylesheet" type="text/css" />

      <!-- Style customizer -->
      <link href="resources/css/style-customizer.css" rel="stylesheet" type="text/css" />

      <link href="resources/css/tablestyle.css" rel="stylesheet" type="text/css" />

    </head>

    <body>

      <c:choose>
        <c:when test="${role=='host'}">
          <jsp:include page="hostmenuheader.jsp" />
        </c:when>
        <c:otherwise>
          <jsp:include page="adminmenuheader.jsp" />
        </c:otherwise>
      </c:choose>

      <section class="login-form register-img dark-bg" style="background: url(resources/images/04.png) no-repeat 0 0; background-size: cover;">
        <section class="container">
          <div class="row">
            <h4 class="title  text-white text-center">Add/Edit Events</h4>

            <div class="text-center">

              <img id="myImg" src="${event.imgUrl}" alt="your image" style="width: 1200px; height: 400px;" />
              <input id="browsebtn" type='file' />
              <!-- <button id="confirmbtn" class="button" onclick="showImgDetails()">Confirm Image</button> -->

            </div>

            <div id="form1">

              <div class="col-md-6 col-md-offset-3">
                <div class="section-field mb-30" style="" align="center">
                  <div class="field-widget">

                    <i id="eventidtag" class="fa fa-tag" aria-hidden="true"></i>

                    <input id="form1eventid" path="id" value="${event.id}" placeholder="Event ID" />

                  </div>
                </div>


              </div>
            </div>
            <div style="clear:both"></div>

            <div class="text-center"><button id="confirmbtn" class="button btn-lg btn-theme full-rounded center-icn" onclick="showImgDetails()">Confirm Image</button></div>


            <div id="form2">
              <form:form id="eventform" method="POST" action="/datingapp/saveEvent">

                <table id="sourcetable" align="center" style="border-radius: 0px;">

                  <div class="col-md-6 col-md-offset-3">



                    <div class="section-field mb-30" style="" align="center">
                      <div class="field-widget">
                        <i class="fa fa-tag" aria-hidden="true"></i>
                        <form:input id="form2eventid" path="id" value="" placeholder="Event ID" />
                      </div>
                    </div>

                    <div class="section-field mb-30" style="" align="center">
                      <div class="field-widget">
                        <i class="fa fa-font" aria-hidden="true"></i>
                        <form:input path="name" value="${event.name}" placeholder="Event Name" />
                      </div>
                    </div>

                    <div class="section-field mb-30" style="" align="center">
                      <div class="field-widget">
                        <i class="fa fa-id-card" aria-hidden="true"></i>
                        <form:input path="hostId" value="${event.hostId}" placeholder="Host ID" />
                      </div>
                    </div>

                    <div class="section-field mb-30" style="" align="center">
                      <div class="field-widget">
                        <i class="fa fa-user" aria-hidden="true"></i>
                        <form:input path="hostName" value="${event.hostName}" placeholder="Host Name" />
                      </div>
                    </div>

                    <div class="section-field mb-30" style="" align="center">
                      <div class="field-widget">
                        <!-- <i class="fa fa-user" aria-hidden="true"></i> -->
                        <i><img alt="" src="resources/images/theme.png"></i>
                        <form:input path="theme" value="${event.theme}" placeholder="Event Theme" />
                      </div>
                    </div>

                    <div class="section-field mb-30" style="" align="center">
                      <div class="field-widget">
                        <i class="fa fa-venus-mars" aria-hidden="true"></i>
                        <form:input path="orient" value="${event.orient}" placeholder="Event Sex Orientation" />
                      </div>
                    </div>

                    <div class="section-field mb-30" style="" align="center">
                      <div class="field-widget">
                        <!-- <i class="fa fa-user" aria-hidden="true"></i> -->
                        <i><img alt="" src="resources/images/ageGroup.png"></i>
                        <form:input path="ageGroup" value="${event.ageGroup}" placeholder="Age Group" />
                      </div>
                    </div>

                    <div class="section-field mb-30" style="" align="center">
                      <div class="field-widget">
                        <i class="fa fa-check" aria-hidden="true"></i>
                        <form:input path="approved" value="${event.approved}" placeholder="Event Approved" />
                      </div>
                    </div>

                    <div class="section-field mb-30" style="" align="center">
                      <div class="field-widget">
                        <i class="fa fa-picture-o" aria-hidden="true"></i>
                        <form:input id="eventimg" path="imgUrl" value="" placeholder="Event Image" />
                      </div>
                    </div>

                    <div class="section-field mb-30" style="" align="center">
                      <div class="field-widget">
                        <i class="fa fa-map-marker" aria-hidden="true"></i>
                        <form:input path="state" value="${event.state}" placeholder="State" />
                      </div>
                    </div>

                    <div class="section-field mb-30" style="" align="center">
                      <div class="field-widget">
                        <i class="fa fa-map-marker" aria-hidden="true"></i>
                        <form:input path="city" value="${event.city}" placeholder="City" />
                      </div>
                    </div>

                    <div class="section-field mb-30" style="" align="center">
                      <div class="field-widget">
                        <i class="fa fa-map-marker" aria-hidden="true"></i>
                        <form:input path="zip" value="${event.zip}" placeholder="ZipCode" />
                      </div>
                    </div>

                    <div class="section-field mb-30" style="" align="center">
                      <div class="field-widget">
                        <i class="fa fa-location-arrow" aria-hidden="true"></i>
                        <form:input path="venue" value="${event.venue}" placeholder="Venue" />
                      </div>
                    </div>

                    <div class="section-field mb-30" style="" align="center">
                      <div class="field-widget">
                        <!-- <i class="fa fa-user" aria-hidden="true"></i> -->
                        <i><img alt="" src="resources/images/openclose.png"></i>
                        <form:input path="open" value="${event.open}" placeholder="Event Open/Closed" />
                      </div>
                    </div>

                    <div class="section-field mb-30" style="" align="center">
                      <div class="field-widget">
                        <i class="fa fa-list" aria-hidden="true"></i>
                        <form:input path="desc" value="${event.desc}" placeholder="Description" />
                      </div>
                    </div>

                    <div class="section-field text-uppercase text-center mt-20">
                      <input class="button  btn-lg btn-theme full-rounded right-icn" name="submit" type="submit" value="SUBMIT">
                    </div>
                  </div>


                </table>
              </form:form>
            </div>

          </div>
        </section>
      </section>


    </body>

    </html>

And my JavaScript is as follows:

<!-- jquery  -->
<
script type = "text/javascript"
src = "resources/js/jquery.min.js" > < /script>

  <!-- bootstrap -->
  <
  script type = "text/javascript"
src = "resources/js/bootstrap.min.js" > < /script>

  <!-- mega-menu -->
  <
  script type = "text/javascript"
src = "resources/js/mega_menu.js" > < /script>

  <!-- style customizer  -->
  <
  script type = "text/javascript"
src = "resources/js/style-customizer.js" > < /script>

  <!-- custom -->
  <
  script type = "text/javascript"
src = "resources/js/custom.js" > < /script>

  <!-- Firebase -->
  <
  script src = "https://www.gstatic.com/firebasejs/4.3.1/firebase.js" > < /script>

  <!-- Table Sorter Function -->
  <
  script type = "text/javascript" >
  var pickedup;
$(document).ready(function() {

  $("#sourcetable tbody tr").on("click", function(event) {

    // Get back to where it was before if it was selected :
    if (pickedup != null) {
      // Set background color of row to white
      pickedup.css("background-color", "#fff");

      // Set text color to gray
      pickedup.css("color", "gray");
    }

    // Fetch name of clicked event
    $("#fillname").val($(this).find("td").eq(1).html());

    // Set background color of row to yellow
    $(this).css("background-color", "#FFBC05");

    // Set text color to white
    $(this).css("color", "#fff");

    pickedup = $(this);
  });
}); <
/script>

<
script type = "text/javascript" >

  $(function() {
    $("#form2").hide(); // try to hide form
    $("#confirmbtn").on("click", function() {

      //alert("Show mesg");
      $("#form1eventid").hide();
      $("#eventidtag").hide();

      $("#browsebtn").hide();
      $("#confirmbtn").hide();

      var form1eventid, form2eventid;
      form1eventid = document.getElementById("form1eventid").value;
      document.getElementById("form2eventid").value = form1eventid;

      $("#form2").show();

      //$("#form1", "#form2").toggle();
    });
  });

/* Function to display image on screen before uploading */
$(function() {
  $(":file").change(function() {
    if (this.files && this.files[0]) {
      var filename;
      var reader = new FileReader();
      reader.onload = imageIsLoaded;
      reader.readAsDataURL(this.files[0]);

      // Get file name
      filename = this.files[0].name;
      //alert(filename);
    }
  });
});

/* Function to load image on page load event */
function imageIsLoaded(e) {
  $('#myImg').attr('src', e.target.result);
};

/* Function to display image details */
function showImgDetails() {

  // Initialize Firebase
  var config = {

    apiKey: "*****",
    authDomain: "*****",
    databaseURL: "*****",
    projectId: "*****",
    storageBucket: "*****",
    messagingSenderId: "*****"
  };
  firebase.initializeApp(config);

  // Get Image and Image Name
  var file = document.querySelector('input[type=file]').files[0];
  var oldpicname = document.querySelector('input[type=file]').files[0].name;

  // Get a reference to the storage service, which is used to create references in your storage bucket
  var storageRef = firebase.storage().ref();

  // Create a reference to the file to delete
  var desertRef = storageRef.child('EventPosters/' + oldpicname);

  // Delete the file
  desertRef.delete().then(function() {
    // File deleted successfully
  }).catch(function(error) {
    // Uh-oh, an error occurred!
  });

  // Create the file metadata
  var metadata = {
    contentType: 'image/jpeg'
  };


  // Upload file and metadata to the object 'EventPosters/your_selected_image.jpg'
  var uploadTask = storageRef.child('EventPosters/' + file.name).put(file, metadata);

  // Listen for state changes, errors, and completion of the upload.
  uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED, // or 'state_changed'
    function(snapshot) {
      // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
      var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
      console.log('Upload is ' + progress + '% done');
      switch (snapshot.state) {
        case firebase.storage.TaskState.PAUSED: // or 'paused'
          console.log('Upload is paused');
          break;
        case firebase.storage.TaskState.RUNNING: // or 'running'
          console.log('Upload is running');
          break;
      }
    },
    function(error) {

      // A full list of error codes is available at
      // https://firebase.google.com/docs/storage/web/handle-errors
      switch (error.code) {
        case 'storage/unauthorized':
          // User doesn't have permission to access the object
          break;

        case 'storage/canceled':
          // User canceled the upload
          break;

        case 'storage/unknown':
          // Unknown error occurred, inspect error.serverResponse
          break;
      }
    },
    function() {
      // Upload completed successfully, now we can get the download URL
      var downloadURL = uploadTask.snapshot.downloadURL;
      console.log('Upload completed...');
      console.log('Download URL is - ' + downloadURL);
      document.getElementById("eventimg").value = downloadURL;
    });
} <
/script>

My Firebase Storage Rules are as follows :

service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read,
            write: if request.resource == null || 
                        (request.resource.contentType.matches('image/jpeg')
                        || request.resource.contentType.matches('image/png')
                        || request.resource.contentType.matches('image/gif')
                        && request.resource.size < 2 * 1024 * 1024)
    }
  }
}

What I am trying to do is as follows :

  1. Click on Browse button and choose an image
  2. On clicking Confirm button I need to first delete previous image from firebase
  3. When previous image is deleted, then upload new image to firebase
  4. And finally get the download url for this new image.

Kindly let me know how to go about this. Any help is much appreciated.

javascriptjqueryhtmlfirebasefirebase-storage

Answers

comments powered by Disqus