Using the servlet to upload file functions

Source: Internet
Author: User
Tags getmessage

1.servlet just add a comment and use Request.getpart to get the value of the file, which is the servlet3.0 API

2. The form needs to add an attribute enctype= "Multipart/form-data"

Now attach the code

Form:

 <formMethod= "POST"Action= "Upload"enctype= "Multipart/form-data" >File:<inputtype= "File"name= "File"ID= "File" /> <BR/>Destination:<inputtype= "text"value= "F:"name= "Destination"/>            <BR/>            <inputtype= "Submit"value= "Upload"name= "Upload"ID= "Upload" />
</form>

Servlet:

Add these two notes to the class's reputation

@WebServlet (name = "Fileuploadservlet", Urlpatterns = {"/upload"})
@MultipartConfig

Custom methods:

The ProcessRequest method is to get the value of the file

protected voidProcessRequest (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {response.setcontenttype ("Text/html;charset=utf-8");
Request.setcharacterencoding ("Utf-8");
      
Get pathFinalString Path = request.getparameter ("Destination");
Get the value of a fileFinalPart Filepart = Request.getpart ("File"); System.out.println (Filepart); FinalString FileName =GetFileName (Filepart); Manipulating files using IO stream outputstream out=NULL; InputStream filecontent=NULL; FinalPrintWriter writer =Response.getwriter (); Try{ out=NewFileOutputStream (NewFile (path +File.separator+fileName)); Filecontent=Filepart.getinputstream (); intRead; Final byte[] bytes =New byte[1024]; while(read = Filecontent.read (bytes))! =-1) {out.write (bytes,0, read); } writer.println ("New file" + FileName + "created at" +path); LOGGER.log (Level.info,"File {0} being uploaded to {1}", Newobject[]{filename, path}); } Catch(FileNotFoundException fne) {writer.println ("You either didn't specify a file to upload or is" + "trying to upload a file to a protected or none Xistent "+" location. "); Writer.println ("<br/> ERROR:" +fne.getmessage ()); LOGGER.log (Level.severe,"Problems during file upload. Error: {0} ", Newobject[]{fne.getmessage ()}); } finally { if(Out! =NULL) {out.close (); } if(Filecontent! =NULL) {filecontent.close (); } if(Writer! =NULL) {writer.close (); } } }

The

GetFileName method is to get the file name

 private  String getfilename (final  Span style= "color: #000000;" > part) { final  String partheader = Part.getheader (" Content-disposition "); LOGGER.log (Level.info,  part Header = {0} ", Partheader);  for  (String content:part.getHeader ("Content-disposition"). Split (";"    Content.substring (Content.indexof ( ' = ') + 1). Trim (). replace ("\" "," " return  null  ;}  

And finally wrote it in the Dopost method.

protected void DoPost (httpservletrequest request, httpservletresponse response) throws servletexception, IOException {processrequest (request, response);}

It's all done here, the effect of the long passing success,

Using the servlet to upload file functions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.