我正在嘗試使用jquery ajax FormData
上傳圖片以製作一個ajax請求至servlet
。但是我總是從servlet獲得錯誤響應。下面是我的代碼:無法使用jquery ajax FormData與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的錯誤函數。我在哪裏犯錯?如果有人能解決我的問題,這將是非常有幫助的。
你得到了什麼錯誤? –
錯誤:{「readyState」:0,「status」:0,「statusText」:「error」} – JPG