AJAX调用不是异步的(JSP)

zvokhttg  于 2022-12-07  发布在  其他
关注(0)|答案(1)|浏览(106)

我正在基于servlet的JSP应用程序中进行一个基于 AJAX 的文件上传任务。我对这个非常陌生,所以很抱歉我缺乏知识。我正在从JSP页面上传文件(abc.jsp)到服务器并在servlet中处理它(fileuploadservlet.java)并返回一个响应,我需要在同一页面的客户端处理该响应(abc.jsp)。我已经实现 AJAX 调用,它可以很好地将文件发送到servlet,处理文件并返回结果。但是由于某些原因,这个过程不是异步的。返回的响应被重定向到带有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();
    
  }

}
toe95027

toe950271#

我认为您的脚本被触发了两次,在$. ajax和表单提交中。
是否尝试在文件上载按钮处添加type ="button"?

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

相关问题