无法与Servlet一起使用jQuery ajax formdata



我试图使用jQuery ajax FormDataservlet提出AJAX请求。但是我总是会从servlet收到错误响应。以下是我的代码:

JSP文件

 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <title>File Upload</title>
    <script>
   function hitThis(){
    alert("hello");
    var form1 = document.getElementById("form1");
  $.ajax( {
    url: 'UploadDocs',
    type: 'POST',
    data: new FormData( form1 ),
    processData: false,
    contentType: false,
    success: function(response) {
    alert("success : ");
        },
    error: function(xhr) {
          alert("error : "+JSON.stringify(xhr));
        //Do Something to handle error
      }
  } );
    }  
    </script>
    </head>
    <body>
    <center>
        <h1>File Upload</h1>
        <form id="form1" class="form-inline" onsubmit="hitThis();">
            Amount : <input type="text" value="232" name="amount"/><br>
            Select file to upload: <input type="file" name="file" size="60" /><br />
            Select file to upload: <input type="file" name="file" size="60" /><br />
            <br /> <input type="submit" value="Upload" />
        </form>
    </center>
    </body>
    </html>

servlet

package org.wpits.ussd;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.json.JSONObject;
import org.wpits.service.DbService;
import org.wpits.ussd.beans.UserDocs;
/**
 * Servlet implementation class UploadDocs
 */
@WebServlet("/UploadDocs")
@MultipartConfig(fileSizeThreshold=1024*1024*2, // 2MB
maxFileSize=1024*1024*10,      // 10MB
maxRequestSize=1024*1024*50)   // 50MB
public class UploadDocs extends HttpServlet {
    private static final long serialVersionUID = 1L;
       private DbService dbService = new DbService();
       private String filePath;
    public UploadDocs() {
        super();
    }
    @Override
    public void init(ServletConfig config) throws ServletException {
        // TODO Auto-generated method stub
        super.init(config);
           filePath = getServletContext().getInitParameter("file-upload"); 
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        String savePath = filePath;
        String amount = request.getParameter("amount");
        System.out.println(amount);
        File fileSaveDir = new File(savePath);
        if (!fileSaveDir.exists()) {
            fileSaveDir.mkdir();
        }
       for (Part part : request.getParts()) {
            String fileName = extractFileName(part);
            if(fileName!=null && !fileName.equals("")){
            InputStream is = part.getInputStream();
            File f = new File(savePath+File.separator+fileName);
            copyInputStreamToFile(is,f);
            }
        }
    }
    private void copyInputStreamToFile( InputStream in, File file ) {
        try {
            OutputStream out = new FileOutputStream(file);
            byte[] buf = new byte[1024*1024*10];
            int len;
            while((len=in.read(buf))>0){
                out.write(buf,0,len);
            }
            out.flush();
            out.close();
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
     private String extractFileName(Part part) {
            String contentDisp = part.getHeader("content-disposition");
            String[] items = contentDisp.split(";");
            for (String s : items) {
                if (s.trim().startsWith("filename")) {
                    return s.substring(s.indexOf("=") + 2, s.length()-1);
                }
            }
            return "";
        }
}

我能够在描述的目录路径上编写图像。但是问题是,我总是被重定向到Ajax的错误响应。另外,每当我重新启动tomcat服务器并尝试上传文件时,我就会在第一次尝试失败后第二次尝试获得" java.io.IOException: org.apache.tomcat.util.http.fileupload.FileUploadBase$IOFileUploadException: Processing of multipart/form-data request failed. Stream ended unexpectedly",上面的书面代码能够编写文件,但对AJAX的错误函数进行了响应。我在哪里犯错?如果有人可以解决我的问题,这将非常有帮助。

使用此格式发射ajax。

//get choosen file
var fileContent = new FormData();
fileContent.append("file",$('input[type=file]')[0].files[0]);
$.ajax({
     type: "POST",
      enctype:"multipart/form-data",
       url: "uploadCsvData",
       data: fileContent,
       processData: false,
       contentType: false,
       success: function(response) {
        }
});

上面代码中的问题只是我以我的形式使用 onsubmit()input type="submit"。必须替换 - 删除onsubmit事件并将onclick事件应用于按钮而不是input type = "submit"。当与基本形式结合使用时,Ajax会导致不匹配。

最新更新