从jsp我需要通过ajax调用上传文件,实习生向servlet发出请求,上传过程完成后我需要控制回ajax函数,以便我可以向用户显示所有导入的数据。
// 这是我的代码
<form id="form1" method="post" enctype="multipart/form-data" action="TestUpload"
onsubmit="validate();" >
Name : <input type="text" name="name" id="name"/><br>
File : <input type="file" name="file" id="file"></input><br>
<input type="submit" value="Submit" ></input>
</form>
// ajax function :
var validate = function() {
var form = $('#form1');
strContent = $.getMultipartData('#'+this.id);
var programId = $('#name').val();
if (programId == "") {
return false;
}
$.ajax( {
type: form.attr('method'),
url: form.attr('action'),
enctype:form.attr('enctype'),
contentType: 'multipart/form-data; boundary='+strContent[0],
data: form.serialize,
success : function(data) {
alert(data);
$('#status').val(data);
}
});
};
和 Servlet 代码使用 mutlipartRequest 处理表单数据。
public void processRequest(HttpServletRequest request,HttpServletResponse response) throws
ServletException,IOException{
System.out.println("Got Request");
File file = null;
response.setContentType("text/plain");
response.setHeader("Access-Control-Allow-Origin", "*");
PrintWriter out = response.getWriter();
String filePath = "c:\\test";
MultipartRequest processFile = new MultipartRequest(request, filePath);
file = processFile.getFile("file");
String fileName = file.getName();
System.out.println("Valule of text field Name is :\t" +
processFile.getParameter("name"));
System.out.println("FileName is :\t" + fileName);
out.println("success");
out.close();
}
//一旦过程完成,我想回复ajax调用我无法找到正确的解决方案。