javascript - Ajax request to send file from jsp to servlet -
following 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 me , need using ajax request (jsp-servlet), following tried 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 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 @ servlet class 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 tell me how impliment following using ajax request. or if type of request not possible. thank you////
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); } });
}
Comments
Post a Comment