File Upload to Server

Source: Internet
Author: User

Uploading to a server using a file requires importing two packages of Commons-fileupload-1.2.2.jar and Commons-io-2.4.jar

The servlet in this article uses the servlet3.0 annotation configuration without having to write the Web. xml file.

Use javaEE6.0 to support servlet3.0 when creating files

Value is the access path
The value of Urlpatterns is also the access path such as
@WebServlet (name= "DemoServlet3", value= "/demoservlet3")
public class DemoServlet3 extends HttpServlet {
...
}

File Upload Form

Method must be a post
Enctype= "Multipart/form-data"

For example

<form action= "${pagecontext.request.contextpath}/uploadservlet" method= "post" enctype= "Multipart/form-data" > Username: <input type= "text" name= "username"/><br/> Please select File: <input type= "file" Name= "Nfile"/><br/ ><input type= "Submit" value= "Upload"/></form>

  

Steps to create a form

1. Create Diskfileitemfactory Factory
Diskfileitemfactory dif = new Diskfileitemfactory ();
2. Create a Servletfileupload object
Servletfileupload SFU = new Servletfileupload (DIF);
3. Determine if the form submission is Multipart/form-data
Boolean ismultipart = sfu.ismultipartcontent (request);

The overall code is as follows:

Import Java.io.file;import java.io.ioexception;import Java.io.printwriter;import Java.util.arrays;import Java.util.list;import Javax.servlet.servletexception;import Javax.servlet.annotation.webservlet;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Org.apache.commons.fileupload.fileitem;import Org.apache.commons.fileupload.fileuploadexception;import org.apache.commons.fileupload.disk.DiskFileItemFactory ; Import org.apache.commons.fileupload.servlet.ServletFileUpload; @WebServlet (name= "Uploadservlet", urlpatterns= "/ Uploadservlet ") public class Uploadservlet extends HttpServlet {public void doget (HttpServletRequest request, HttpServletResponse response) throws Servletexception, IOException {System.out.println ("------------ File Upload----------------");//File upload path My files are uploaded in the new file folder under F:\tomcat7\webapps\javaweb. String readpath= This.getservletcontext (). Getrealpath ("file");//create Diskfileitemfactory factory diskfileitemfactoryDif=new diskfileitemfactory (); Servletfileupload sfu=new servletfileupload (DIF); Boolean immultipart = Sfu.ismultipartcontent (request); if ( Immultipart) {//File upload try {//parse request get form element that is all submission information for form list<fileitem> items =sfu.parserequest (request); if (items!= NULL) {for (Fileitem item:items) {if (Item.isformfield ()) {///determine if it is a normal field (that is, an uploaded user name password, etc.) String Filename=item.getfieldna Me (); String value=item.getstring ("UTF-8");     System.out.println (filename+ "----------" +value); Read the user name password and other files}else{//is the file to be uploaded//get the uploaded filename string filename=item.getname ();          System.out.println ("uploaded file name:" +filename); Create a new file object The first parameter puts the file on the output path of document file=new files (readpath,filename);//Start uploading item.write (file); System.out.println ("File Upload succeeded! The file name is "+filename";}}}} catch (Fileuploadexception e) {//Todo auto-generated catch Blocke.printstacktrace ();} catch (Exception e) {//Todo auto-g Enerated catch Blocke.printstacktrace ();}}} public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {DOget (request, response);} 

  

If we add
Limit the type and size of file uploads
Type:
list<string> filtypes = arrays.aslist ("JPG", "png", "GIF", "BMP");

Size:
Set maximum limit for individual files
Upload.setsizemax (1024*30);

Get the suffix of the upload file name:
String FileType = filename.substring (Filename.lastindexof (".") +1);
System.out.println ("suffix:" +filetype);
Boolean flag = Filtypes.contains (FileType);

The complete code is as follows:

Package Cn.bdqn.demo;import Java.io.file;import java.io.ioexception;import java.util.arrays;import java.util.List; Import Javax.servlet.servletexception;import Javax.servlet.annotation.webservlet;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Org.apache.commons.fileupload.fileitem;import Org.apache.commons.fileupload.fileuploadbase;import Org.apache.commons.fileupload.fileuploadexception;import Org.apache.commons.fileupload.disk.diskfileitemfactory;import Org.apache.commons.fileupload.servlet.ServletFileUpload, @WebServlet (name= "Uploadservlet", value= "/uploadservlet ") public class Uploadservlet extends HttpServlet {private static final long Serialversionuid = -2590255173244980573l;publ IC void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { SYSTEM.OUT.PRINTLN ("----File upload---------"); Response.setcontenttype ("text/html; Charset=utf-8 "); response.setcharacteRencoding ("UTF-8"); Request.setcharacterencoding ("UTF-8");//Gets the path of the uploaded file string realpath = This.getservletcontext (). Getrealpath ("Files"); System.out.println ("Upload path:" +realpath);//1. Create Diskfileitemfactorydiskfileitemfactory dif = new Diskfileitemfactory () ;//2. Create Servletfileupload object Servletfileupload SFU = new Servletfileupload (DIF);//3. Determine if a form submission is multipart/ Form-databoolean Ismultipart = sfu.ismultipartcontent (Request), if (Ismultipart) {//File upload//servletfileupload parse request    Gets the collection of elements list<string> filtypes = arrays.aslist ("JPG", "png", "GIF", "BMP");//limits the size of a single file Sfu.setsizemax (1024*30); Maximum 30KBtry {list<fileitem> items = sfu.parserequest (Request), if (Items!=null) {for (Fileitem item:items) {if ( Item.isformfield ()) {//Determine if it is a normal field string fieldName = Item.getfieldname (); String value = item.getstring ("UTF-8"); System.out.println (fieldname+ "---" +value);} else{//is the file file upload//Get upload filename of string filename = Item.getname ();//Determine if the file type matches://Gets the suffix string fileType = filename.substring ( Filename.lastindexof (".") +1); System.out.pRintln ("suffix:" +filetype); Boolean flag = Filtypes.contains (FileType); if (flag) {System.out.println ("uploaded filename:" +filename) ;//Create a new file object The first parameter puts the file upload path files = new file (Realpath, fileName);//Start uploading item.write (file); System.out.println ("File Upload succeeded! "); Response.getwriter (). Print (" File Upload succeeded! ");} Else{response.getwriter (). Print ("Upload failed!" File type must be jpg,png,gif,bmp! ");}}}}} catch (Fileuploadbase.sizelimitexceededexception e) {System.out.println ("Upload failed, file is too large, the maximum limit for a single file is:" +sfu.getsizemax () + "bytes!"); Response.getwriter (). Print ("The upload failed, the file is too large, the maximum limit for a single file is:" +sfu.getsizemax () + "bytes!");} catch (Exception e) {e.printstacktrace ();}} Else{response.getwriter (). Print ("The form is not multipart/form-data, file upload failed!") ");}} public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { Doget (request, Response);}}

  

File Upload to Server

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.