AJAX 调用未进行异步 (JSP)

AJAX call is not going Asynchronous (JSP)

我正在基于 JSP 应用程序中基于 servlet 的 AJAX 文件上传任务。我对此很陌生,因此为我缺乏知识而道歉。 我正在将文件从 JSP 页面 (abc.jsp) 上传到服务器并在 servlet (fileuploadservlet.java) 中处理它并返回一个我需要在客户端处理的响应页(abc.jsp)。 我已经实现了 AJAX 调用,它可以很好地将文件发送到 servlet,处理文件并且 returns 结果也很好。但由于某种原因,这个过程不是异步的。返回的响应被重定向到带有 URL 的 servlet 页面,比方说 http://localhost:8080/projectName/fileuploadservlet 我需要让它异步,这是 AJAX 的正常行为。 任何建议或指出我所犯的错误将不胜感激。

这是HTML脚本

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

这是Javascript代码

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);
                        
                    }
                });
               }
           });

这是 servlet 代码(整个 servlet 文件):

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();
    
  }

}

我认为您的脚本被触发了两次,在 $.ajax 和表单提交中。

尝试在您的文件上传按钮上添加一个 type="button"?

<button id="uploadFileButton" type="button" class="btn btn-outline-dark">Upload</button>