0

以下是使用 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>

小服务程序

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 请求来执行以下操作。或者如果这种类型的请求是不可能的。谢谢////

4

1 回答 1

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

}

http://jsfiddle.net/ajk7J/

于 2013-05-04T09:30:49.290 回答