How to Use servletfileupload

Source: Internet
Author: User

1. first, we should create a storage location for the uploaded files. Generally, the location is divided into temporary and real folders. Then we need to obtain the absolute path of these two folders, in servlet, we can do this.

ServletContext application = this.getServletContext();  String tempDirectory = application.getRealPath(Constant.TEMP_DIRECTORY) + "/";  String realDirectory = application.getRealPath(Constant.REAL_DIRECTORY) + "/";




Then a file factory is created, that is, a parameter in the warehouse, indicating the size of the data to be stored and flushed,

FileItemFactory factory = new DiskFileItemFactory(Constant.SIZE_THRESHOLD,new File(tempDirectory));  ServletFileUpload upload = new ServletFileUpload(factory);

2. Set uploaded files

Upload. setsizemax (500*1024*1024); // sets the maximum value of this upload to 500 mb.

3. parse the Request body and obtain the uploaded file. If no exception is thrown, the actual path is written.

List <fileitem> List = upload. parserequest (request); iterator <fileitem> iter = List. iterator (); While (ITER. hasnext () {fileitem item = ITER. next (); // item. isformfield () is used to determine whether the current object is data in the file form field. If the returned value is true, it is not a common form field if (item. isformfield () {system. out. println ("common form field" + item. getfieldname (); system. out. println (item. getstring ("UTF-8");} else {// system. out. println ("file form field" + item. getfieldname ();/** only the file form field writes the content of this object to the real folder */string lastpath = item. getname (); // get the name of the uploaded file lastpath = lastpath. substring (lastpath. lastindexof (". "); string filename = UUID. randomuuid (). tostring (). replace ("-", "") + lastpath; item. write (new file (realdirectory + filename ));




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.