java - File Uploading with Servlets? -
note:
before reading question , answer, please check input element has name
attribute.
i trying upload file using servlet. eclipse console shows no errors. file not getting uploaded. me, seems fine. making mistake somewhere.
in console
inside servlet //printed code items: [] // printed cdoe
html code:
<form action="imageuploadservlet" method="post" enctype="multipart/form-data"> <table> <tr> <td><label>select image: </label></td> <td><input type="file" id="sourceimage" /></td> <tr> <td colspan="3"> <input type="submit" value="upload"/><span id="result"></span> </td> </tr> </table> </form>
servlet code:
protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { boolean ismultipart = servletfileupload.ismultipartcontent(request); system.out.println("inside servlet"); if(!ismultipart){ system.out.println("form type not multipart/form-data"); system.out.println("file not uploaded"); } else { fileitemfactory dfit = new diskfileitemfactory(); servletfileupload sfu = new servletfileupload(dfit); list alist = null; try { alist = sfu.parserequest(request); system.out.println("items: "+alist); } catch (fileuploadexception fue) { fue.printstacktrace(); } iterator itr = alist.iterator(); while(itr.hasnext()) { fileitem fi = (fileitem) itr.next(); if(fi.isformfield()) { system.out.println("file name: "+fi.getfieldname()); system.out.println("file size: "+fi.getsize()); try { file f = new file("d:/myuploads/", fi.getname()); fi.write(f); } catch (exception e) { e.printstacktrace(); } } else { system.out.println("it's not form item;"); } } } } }
any suggestions appreciated.
thanks!
there 2 problems:
first, need give field name
. becomes request parameter name.
<input type="file" id="sourceimage" name="sourceimage" />
second, need handle file uploads in else
case of fileitem#isformfield()
per commons fileupload guide. code ignoring them , doing sysout.
if (item.isformfield()) { // process regular form field (input type="text|radio|checkbox|etc", select, etc). string fieldname = item.getfieldname(); string fieldvalue = item.getstring(); // ... (do regular form field processing job here) } else { // process form file field (input type="file"). string fieldname = item.getfieldname(); string filename = filenameutils.getname(item.getname()); // ... (do uploaded file job here) file file = new file("d:/myuploads/", filename); item.write(file); }
note need use filenameutils#getname()
extract file name, because msie browser incorrectly sends full client side file path along file name. see commons fileupload faq.
you need keep in mind approach overwrite uploaded file same name. may want add autogenerated suffix filename.
Comments
Post a Comment