Java Component commons fileupload implement file upload function _java

Source: Internet
Author: User
Tags file upload uuid

Apache provides the Commons-fileupload jar package implementation file upload is really very simple, recently to use servlet/jsp to do a picture upload function, found a lot of information on the Internet, mostly based on the struts framework introduced, Others, although also introduced common-fileupload upload, but those examples are older, some classes are now discarded.

Through research and learning summary, finally completed this upload function, below share with you.

Case scenario

A library background management interface, you need to provide the ability to upload book pictures and eventually appear in the page.

Implementation effect

Enter Add book page, the default display of a picture "no breakthrough" (long width is 200px), provide a button "upload picture", the following figure effect.

Click the "Upload Picture" button to eject the upload interface through the modal window, as shown in the following figure.

Through the "Browse" button to select the specified picture, click the "Upload" button to upload, if the Upload success pop-up success prompts, the user clicks "OK" after the pop-up window and automatically show the new picture on the page, as shown in the following figure.

Code implementation

① first create an Add Book page: bookadd.jsp

Page ID photo_id hidden tag is used to store picture paths, facilitate submission to the background to the database, id img_id tags used to display pictures, all pictures are stored under the server, easy to read. Then a key JS, click button through the Mode window pop-up upload page, in the pop-up mode window defines a variable win, which is used to get the pattern window returns the image path value.

(Note: Because of security issues pictures can not be stored at random, the project deployed in the server, the picture can only be placed under the server to view, if you must read the pictures under the current server to configure the server's virtual directory)

  
 

② Create upload image page, bookupload.jsp

Note Be sure to define <base> tag, the current mode window is closed to return data to the parent form,<form> label and set a property enctype= "Multipart/form-data" so that the file submitted can be retrieved by the background, Click the "Upload" button to transfer files to the background, the rest of the play is the background upload processing.

 
 

③ Create a normal servlet, only some of the key code is provided below

The

  Red Code section is the key code to upload, and the other is as embellishment. Complete these three steps, a simple upload is realized.

public class Bookservlet extends HttpServlet {private String Uploadpath = "eshop/upload/";//upload file directory private Stri ng TempPath = "eshop/uploadtmp/"; 
  
 Temporary file directory private String serverpath = null; 
 
 private int sizemax = 3;//picture maximum upper limit private string[] FileType = new string[]{". jpg", ". gif", ". bmp", ". png", ". jpeg", ". ico"};  
  public void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { 
  Serverpath = Getservletcontext (). Getrealpath ("/"). Replace ("\", "/"); When the servlet is initialized, if the upload file directory does not exist, automatically creates if (!new file (Serverpath+uploadpath). Isdirectory ()) {New File (Serverpath+uploadpat 
  h). Mkdirs (); 
  } if (!new file (Serverpath+temppath). Isdirectory ()) {New file (Serverpath+temppath). Mkdirs (); } <span style= "color: #ff0000;" >diskfileitemfactory factory = new Diskfileitemfactory ();</span> factory.setsizethreshold (5*1024); Maximum cache Factory.setrepository (new file (Serverpath+temppath));//Temporary file directory <sPan style= "color: #ff0000;" >servletfileupload upload = new Servletfileupload (Factory);</span> Upload.setsizemax (sizemax*1024*1024); 
  File maximum upper bound String FilePath = null; try {<span style= "color: #ff0000;" 
    >List<FileItem> items = upload.parserequest (request) </span>//get all file lists for (Fileitem Item:items) { Gets the file name, which includes the path <span style= "color: #ff0000;" 
      
     >if (!item.isformfield ()) {</span>//filename String filename = item.getname (). toLowerCase (); if (Filename.endswith (filetype[0)) | | Filename.endswith (filetype[1]) | | Filename.endswith (filetype[2]) | | Filename.endswith (filetype[3]) | | Filename.endswith (filetype[4]) | | 
      Filename.endswith (Filetype[5])) {String uuid = Uuid.randomuuid (). toString (); 
      FilePath = serverpath+uploadpath+uuid+filename.substring (Filename.lastindexof (".")); <span style= "color: #ff0000;" >item.write (New File (FilePath));</span> printwriter pw = Response.getwriter (); Pw.write ("<script>alert"); Window.returnvalue= ' +uploadpath+uuid+filename.substring ( Filename.lastindexof (".")) 
      + "'; Window.close ();</script>"); 
      Pw.flush (); 
     Pw.close (); 
      }else{Request.setattribute ("errormsg", "Upload failed, please confirm that the uploaded file exists and the type is picture!"); 
     Request.getrequestdispatcher ("/admin/bookupload.jsp"). Forward (request, response); 
   catch (Exception e) {e.printstacktrace ()}}}; 
   Request.setattribute ("ErrorMsg", "Upload failure, please confirm that the uploaded file size can not exceed the" +sizemax+ "M"); 
  Request.getrequestdispatcher ("/admin/bookupload.jsp"). Forward (request, response); 
 } 
   
 }

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.