我试图向servlet
发出ajax请求,要求使用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服务器并尝试上传文件时,我都会得到&#34; java.io.IOException: org.apache.tomcat.util.http.fileupload.FileUploadBase$IOFileUploadException: Processing of multipart/form-data request failed. Stream ended unexpectedly
&#34;在第一次尝试因错误而失败后的第二次尝试,上面编写的代码能够写入文件但是抛出对Ajax的错误函数的响应。我哪里弄错了?如果有人可以解决我的问题,将会非常有帮助。
答案 0 :(得分:2)
使用此格式触发ajax。
List<Foo> fooList = repository.findAll();
Pageable pg = new PageRequest(1, 20); //
Page<Foo> pageFoo = new PageImpl<Foo>(fooList, pg, fooList.size());
final List<Foo> iterable = pageFoo.getContent();
for(Foo foo : iterable) {
.....
}
答案 1 :(得分:0)
上述代码中的问题只是我在表单中使用onsubmit()
和input type="submit"
。必须将其替换为 - 删除onsubmit
事件并将onclick
事件应用于按钮而不是input type = "submit"
。与基本表单结合使用时,Ajax会不匹配。