Ajax请求将文件从jsp发送到servlet

Ajax request to send file from jsp to servlet

本文关键字:servlet jsp 请求 文件 Ajax      更新时间:2023-09-26

以下是使用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请求实现以下操作吗。或者如果这种类型的请求是不可能的。谢谢////

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);
    }
 });

}

请参阅http://jsfiddle.net/ajk7J/