Home > Software engineering >  AJAX call is not going Asynchronous (JSP)
AJAX call is not going Asynchronous (JSP)

Time:04-20

I am working on a AJAX based file upload task in servlets based JSP application. I am very new to this so apologies for my lack of knowledge. I am uploading file from a JSP page (abc.jsp) to server and processing it in a servlet (fileuploadservlet.java) and returning a response which I need to process on the client side on the same page (abc.jsp). I have implemented AJAX call which sends file to the servlet fine, processes the file and returns the result fine as well. But this process is not asynchronous for some reason. The returned response is being redirected to the servlet page with URL, let's say http://localhost:8080/projectName/fileuploadservlet I need to make it asynchronous which is normal behavior of AJAX. Any suggestion or pointing out the mistake that I am committing would be greatly appreciated.

Here is the HTML script

<form method="post" id= "csvUploadForm"  action="fileuploadservlet" enctype="multipart/form-data">
                <div >
                    
                    <input type="file" name="file" id="fileUpload" accept=".csv" />
                    
                </div>
                <div >
                    
                    <button id="uploadFileButton"  >Upload</button>
            
                    <button type="button"  data-dismiss="modal">Close</button>
                </div>
                 </form>

Here is the Javascript code

document.getElementById('uploadFileButton').addEventListener('click', function(){
               
               var attachment = document.getElementById('fileUpload').value;
               if(attachment == "")
                   {
                        alert('Please attach file first');
                   }
               else
               {
               var form = $("#csvUploadForm");
               var data = new FormData(form);
               var url = form.attr('action');
                $.ajax({
                    type: form.attr('method'),
                    enctype : 'multipart/form-data',
                    url: url,
                    data: data,
                    
                    contentType : false,
                    dataType: "json", // Specifies the data type returned from server
                    success : function(responseText) {
                        alert("results: " responseText);
                        
                    }
                });
               }
           });

Here is the servlet code (Whole servlet file):

import java.io.*;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;


@WebServlet(name = "FileUploadServlet", urlPatterns = { "/fileuploadservlet" })
@MultipartConfig(
  fileSizeThreshold = 1024 * 1024 * 1, // 1 MB
  maxFileSize = 1024 * 1024 * 10,      // 10 MB
  maxRequestSize = 1024 * 1024 * 100   // 100 MB
)
public class FileUploadServlet extends HttpServlet {

  private final String csvFileStoragePath = "D:\\Experiment\\APTCT";
  private static Pattern fileExtnPtrn = Pattern.compile("([^\\s] (\\.(?i)(txt|csv))$)");
  
  private static boolean validateFileExtn(String file){
      
      Matcher mtch = fileExtnPtrn.matcher(file);
      if(mtch.matches()){
          return true;
      }
      return false;
  }
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    /* Receive file uploaded to the Servlet from the HTML5 form */
    Part filePart = request.getPart("file");
    String fileName = filePart.getSubmittedFileName();
    
    PrintWriter output = response.getWriter();
    //output.println(fileName);
    
    List<String> resultList=new ArrayList<String>(); 
    List<String> errorList=new ArrayList<String>();  
    
    //Check file extension
    if(!validateFileExtn(fileName))
    {
        //Send error to client
        return;
    }
    //<Get current directory and see if APCT folder exist. If it doesn't exist then create it.>
    
    File dir = new File(csvFileStoragePath);
    if (!(dir.exists() )) {
        dir.mkdirs();
        
    }
    //</Get current directory and see if APCT folder exist. If it doesn't exist then create it.>
    for (Part part : request.getParts()) {
      part.write(csvFileStoragePath "\\" fileName);
    }


    try {
        File fileReaderObject = new File(csvFileStoragePath "\\" fileName);
        Scanner fileReader = new Scanner(fileReaderObject);
        int numberOfLines = 0;
        int rowNumber = 0;
        int numberOfLinesProcessed = 0;
        while (fileReader.hasNextLine()) {
          rowNumber   ; 
          String line = fileReader.nextLine();
          String[] words = line.split(",");
          if(words.length == 1)
          {
              String[] stringArray = words[0].split("");
              String[] processedStringArray = PreProcessor.process(stringArray);
              try
              {
                  Distance d = new Distance(processedStringArray, processedStringArray);
                  String jsonInfo = d.getOutputAsJSON();
                  resultList.add(jsonInfo);
                  numberOfLinesProcessed  ;
                  output.println(jsonInfo);
                  System.out.println(jsonInfo);
              }
              catch (Exception e) {
                e.printStackTrace();
                errorList.add("{\"error\" for row number " rowNumber ": \""   e.getMessage()   "\"}");
                //output.print("{\"error\": \""   e.getMessage()   "\"}");
              }
          }
          else if(words.length >= 2)
          {
              String[] stringArray1 = words[0].split("");
              String[] stringArray2 = words[1].split("");
              String[] processedStringArray1 = PreProcessor.process(stringArray1);
              String[] processedStringArray2 = PreProcessor.process(stringArray2);
              try
              {
                  Distance d = new Distance(processedStringArray1, processedStringArray2);
                  String jsonInfo = d.getOutputAsJSON();
                  resultList.add(jsonInfo);
                  numberOfLinesProcessed  ;
                  output.println(jsonInfo);
                  //JSONObject json = new JSONObject(jsonInfo); // Convert text to object
                  System.out.println(jsonInfo);
              }
              catch (Exception e) {
                e.printStackTrace();
                errorList.add("{\"error\" for row number " rowNumber ": \""   e.getMessage()   "\"}");
                //output.print("{\"error\": \""   e.getMessage()   "\"}");
              }
          }
          else
          {
              errorList.add("{\"error\" for row number " rowNumber ": \" Empty Row.\"}");
          }
          
          numberOfLines  ;
          //System.out.println(line);
        }
        fileReader.close();
        if(numberOfLines == 0)
        {
            //Send error to client that file is empty.
            return;
        }
        //output.print(resultList.toArray());
        //output.print(errorList.toArray());
        output.print(numberOfLinesProcessed);
        System.out.println("Number of processed lines: " numberOfLinesProcessed);
      } catch (FileNotFoundException e) {
        System.out.println("An error occurred. "   e.getMessage());
        e.printStackTrace();
      }
    //*/
    output.flush();
    output.close();
    
  }

}

CodePudding user response:

I think your script is triggered twice, in the $.ajax and the form submit.

try adding a type="button" at your file upload button?

<button id="uploadFileButton" type="button" >Upload</button>
  • Related