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 ));