我正在基于 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();
}
}
uj5u.com熱心網友回復:
我認為您的腳本在 $.ajax 和表單提交中被觸發了兩次。
嘗試在檔案上傳按鈕上添加 type="button" ?
<button id="uploadFileButton" type="button" class="btn btn-outline-dark">Upload</button>
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/458802.html
