使用struts框架
完成了以下操作JSP
<html:form action="/uploadDrawing" method="post" enctype="multipart/form-data">
<input type="file" name="attachfile" class="regi_textbox"/>
<input type="submit" name="button" class="update_but" value="Upload File" />
</html:form>
表格
private FormFile attachfile;
public FormFile getAttachfile() {
return attachfile;
}
public void setAttachfile(FormFile attachfile) {
this.attachfile = attachfile;
}
动作类
FormFile attachfile = uploadDrawingForm.getAttachfile();
这对我来说很好,但是我需要使用ajax请求(jsp-servlet)来执行此操作,以下是我尝试过没有成功的事情---
JSP
<script>
function dynamicUpload()
{
alert("function played");
var fd = new FormData($("attachfileform"));
fd.append( 'file', input.files[0] );
alert(fd);
$.ajax({
url: 'UploadDrawingServlet',
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
alert(data);
}
});
}
</script>
<form enctype="multipart/form-data" method="post" action="" id="attachfileform" name="attachfileform" >
<input type="file" name="attachfile" class="regi_textbox"/>
<input type="button" class="update_but" value="Upload File" onclick="dynamicUpload()"/>
</form>
的Servlet
public class UploadDrawingServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String file = request.getParameter("data");
}
}
对于我提供的web.xml中的映射
<servlet>
<servlet-name>UploadDrawingServlet</servlet-name>
<servlet-class>UploadDrawingServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UploadDrawingServlet</servlet-name>
<url-pattern>/UploadDrawingServlet</url-pattern>
</servlet-mapping>
在servlet类中它接收为---
public class UploadDrawingServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Here in servlet class");
String file = request.getParameter("data");
}
}
任何人都可以告诉我在使用ajax请求后如何表达。 或者如果这种类型的请求不可行。 谢谢////
答案 0 :(得分:1)
function dynamicUpload(){
var formElement = $("[name='attachfileform']")[0];
var fd = new FormData(formElement);
var fileInput = $("[name='attachfile']")[0];
fd.append('file', fileInput.files[0] );
console.log(fd);
$.ajax({
url: 'UploadDrawingServlet',
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
console.log(data);
}
});
}