Ajax呼叫不会异步(JSP)

发布于 2025-01-21 10:59:39 字数 7377 浏览 0 评论 0原文

我正在基于Servlet的JSP应用程序中的基于AJAX的文件上传任务。我对此非常陌生,因此为我缺乏知识而道歉。 我将文件从JSP页面(ABC.JSP)上传到服务器并在Servlet(FileUploadServlet.java)中处理,并返回我需要在同一页面上的客户端(abc.jsp)上处理的响应。 我已经实现了AJAX调用,该调用将文件发送到Servlet Fine,处理文件并返回结果罚款。但是由于某种原因,此过程并不是异步。返回的响应正在用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();
    
  }

}

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 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>

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

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

十年九夏 2025-01-28 10:59:39

我认为您的脚本是在$ .ajax和表格提交中两次触发的。

尝试在文件上传按钮上添加类型=“按钮”吗?

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

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" class="btn btn-outline-dark">Upload</button>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文