What is preventing the control from transitioning to the script method known as "checkExistence()"?

I am currently working on a file upload program where I am utilizing an ajax call to verify if any file exists with the same name.

Here is the snippet of code:

JSP page

<%@ taglib prefix = "form" uri = "http://www.springframework.org/tags/form"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
   <title>File Upload Example</title>
     <script src="/AjaxWithSpringMVC2Annotations/js/jquery.js"></script>
    <script type="text/javascript">
    function checkExistence() {
                var name = $('#file').val();
                File f=new File(name);
                 var filename=f.getOriginalFileName();
                 document.write(filename);
                 $.ajax({
                type: "POST",
                url: "/FileController/fileexists",
                data: "filename=" + filename,
                  success: function(response){
                if(response==0)
                {
                 ch="zero";
                    document.fileform.choice.value=ch;
                    document.fileform.submit();
                }
            else if(response==1)
                {
                 alertchoice=alert("File already exists !! Do you want me to overwrite it ?");
                if(alertchoice==true || alertchoice.equals(true))
                    {
                    ch="one";
                document.fileform.choice.value=ch;
                document.fileform.submit();
                    }
                else {
                    ch="two";
                    alert("Upload suspended as requested by the user ");
                } }
                  },
                  error: function(e){
                alert('Error: ' + e);
                }
                });
                }
</script>
</head>
<body style="background-color:powderblue;color:Tomato"> 
<br>
<br>
<center><form name="fileform" action="savefile" method = "POST" modelAttribute = "fileUpload"
         enctype = "multipart/form-data">
         Please select a file to upload : 
         <input type = "file" name = "file" id="file"><br><br><br>
         <input type="hidden" name="choice">
         <input type = "button" value ="upload" onClick="checkExistence()">
         <input type="reset" value="Reset">
      </form></center>
      <br>
      <br>
      <center><b> ${message} </b></center>
   </body>
</html>

//controller class

 @RequestMapping(value="/fileexists",method = RequestMethod.POST)    

@ResponseBody public String  checkingForDuplicates(HttpServletRequest req, HttpServletResponse res){
     String filename=req.getParameter("filename");
     int i=isDuplicate(filename);
     return i+"";
 }

When clicking the upload button, the intention is for the control to move to the function checkExistence(). However, this does not seem to be happening. Is there an issue with my code? Additionally, I am using

File f=new File(name); var filename=f.getOriginalFileName();

in the JavaScript function to fetch the filename of the uploaded file. Will this work correctly?

Answer №1

After some adjustments, I managed to find the solution.

  1. First step was to add the jquery plugin

  2. Next, I had to update the ajax call URL from

    url: "/FileController/fileexists" to
    url: "fileexists"

  3. I then made changes in the JSP page to retrieve the name of the uploaded file

    var name = $('#file').val(); File f=new File(name); var filename=f.getOriginalFileName();

    revised code :

    var filename=document.getElementById('file').value;

                    var lastIndex = filename.lastIndexOf("\\");
                     if (lastIndex >= 0) {
                   originalfilename = filename.substring(lastIndex +1);
                    }
    
  4. Lastly, in the controller, I needed to fetch the file name (for duplicate checking)

    before : String filename=req.getParameter("filename");

    updated : String filename=req.getParameter("originalfilename");

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a full feature in jQuery for ajax that triggers before both success and error?

Is there a pre-execution method in jQuery AJAX that runs before the success and error handlers? I'm looking for something that will execute regardless of the response code, but before any other methods. ...

A function that retrieves an array containing elements that exceed a specified number and a given array

Is there a way to create a function that takes an array and a number as parameters, then returns a new array with only the elements from the original array that are greater than the given number? For example: [10, 25, 16, -5, 30, 15, 24] , 16 The output ...

What is preventing me from loading Google Maps within my Angular 2 component?

Below is the TypeScript code for my component: import {Component, OnInit, Output, EventEmitter} from '@angular/core'; declare var google: any; @Component({ selector: 'app-root', templateUrl: './app.component.html', st ...

What is the process for assigning the key to a custom array in React using JSX?

Currently, I am developing a dynamic toolbar that adapts based on different states. The functionality works smoothly as expected, allowing me to include only the necessary buttons at any given time. The challenge arises with React's requirement for k ...

I need to retrieve a date value within a function

When using the input type = date, I am trying to retrieve the selected date value in a function. Here is my code: <input style='display:none;' type='date' value='<?php echo date(Y-m-d);?>' name='date' id ...

Tips for adding a new column to a website

My goal is to inject some custom HTML and CSS into YouTube in order to create a column on the right side that shifts all content towards the left. Essentially, I am trying to replicate the functionality of the Inspect Tool in Chrome. I am working on a Chr ...

What is the best way to incorporate a function within a $.click (jquery) event that utilizes an id directly from the clicked element?

It seems that my title may not be very clear, but I have a jQuery code snippet that is causing some issues. The problem stems from the fact that when I click on an image with the class 'slideimg', I expect a function named slideDo to be executed, ...

Abbreviating AngularJS with JavaScript

While Angular offers the ng shortcut for directives in markup, I am curious about how to implement this in JavaScript code. For example, instead of writing angular.isArray, is it possible to use ng.isArray similar to jQuery ($) or Underscore (_)? ...

Modify the value of a service from the main controller

I have been researching extensively on how to edit a service value from a nested controller. The issue I am facing is that my child controller needs to update a specific value in a service, and this value must be reflected in the parent controller as well. ...

Testing out ajax jquery to see if a semicolon can be removed if it is not preceded by any text

After attempting AJAX jQuery, I received response data. ;first comment;second comment;;;third comment The desired output is as follows: first comment second comment third comment To achieve this, I utilized a method to place text before semicolons on the ...

Retrieve the currently selected element following the button press

My webpage features a Carousel with the following structure: <div class="my-controls"> <button class="button123"> <span class="abc">Next-image</span> </button> </div> <div class="my-carousel"> ...

Simulating anticipated outcome from a service with the Spring testing framework

Looking to create a test case for a Restful web service using the Spring testing framework. I have successfully mocked the service and executed the testcase. However, since the service is mocked, it currently returns an empty response. My objective now is ...

Managing xhr requests using Node.js

I recently delved into the world of nodejs and I must say, I'm quite impressed with it. However, I've hit a snag when attempting to utilize it as a middle-man server/client. Just to clarify, my goal is to use nodejs on the client side to act as ...

Utilizing a PHP Class object in Javascript by accessing its properties within a Javascript function

I'm struggling to access the attributes of an object within a JavaScript function that I created. This object was originally a PHP object that I converted to JSON using json_encode() In my project, there is 1 PHP file and 1 external JS file. In the ...

Is there a way to alter the appearance of an HTML element without an ID using a JavaScript function?

I have a specific goal in mind, but I'm struggling to articulate it concisely. Despite conducting extensive research, none of the suggested solutions seem applicable in my case. Objective: I aim to change the background color of a div based on the da ...

What are some other options besides object-fit?

Currently seeking a replacement for the css object-fit property that functions properly in Firefox and IE. While it works well in Chrome and Opera, it is not compatible with Firefox and IE. Experimented with the imgLiquid Plugin, but encountered issues w ...

Updating serialized $_POST array with new key/value pair using jQuery AJAX

Is there a way to insert additional values into a serialized $_POST array before sending an AJAX request using jQuery? Here's the situation: $('#ajax-preview').on('click', function(e) { e.preventDefault(); var formData = ...

Ajax is experiencing issues when attempting to send data that includes a hyphen character

I've encountered an issue with my code. It looks like this: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ ...

Is it possible for the connectedCallback() method within a Custom Component to have varying interpretations based on the specific context in which it is implemented?

I have recently developed a Custom Component that incorporates a Vue instance: class ContentCardExample extends HTMLElement { connectedCallback() { const card = document.createElement('div'); card.setAttribute("id", "app") card.i ...

Exploring CryptoJS in a Vue.js project

https://github.com/brix/crypto-js I successfully installed CryptoJS using npm i crypto-js. However, I am facing difficulty in integrating it into my project. When I attempt to use the following code: // Decrypt var bytes = CryptoJS.AES.decrypt(cipher ...