Reputation: 839
Following is been done using struts framework
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>
Form
private FormFile attachfile;
public FormFile getAttachfile() {
return attachfile;
}
public void setAttachfile(FormFile attachfile) {
this.attachfile = attachfile;
}
Action class
FormFile attachfile = uploadDrawingForm.getAttachfile();
This works fine for me , but i need to do this using ajax request (jsp-servlet), following is what i tried with no success---
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");
}
}
For mapping in web.xml i have provided
<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>
And at servlet class its receiving as---
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");
}
}
Can anybody tell me how to impliment following using ajax request. or if this type of request is not possible. Thank you////
Upvotes: 0
Views: 3961
Reputation: 685
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);
}
});
}
See http://jsfiddle.net/ajk7J/
Upvotes: 1