Java code:
Public ActionForward add (ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {AddForm addForm = (AddForm) form; ActionErrors errors = new ActionErrors (); try {// get the file to be uploaded FormFile file = addForm. getFile (); System. out. println (file. getContentType (); if (! "Image/pjpeg ". equals (file. getContentType () {errors. add (ActionMessages. GLOBAL_MESSAGE, new ActionMessage ("the file type you selected is incorrect", false); this. addErrors (request, errors); return mapping. findForward ("error");} // get the Upload file Name String filename = file. getFileName (); // get the new file name String newfilename = DataDefine. getDateId () + ". "+ filename. substring (filename. lastIndexOf (". "); String imagespath =" images "+"/"+ newfilename; // Obtain the Server Upload directory String dir = this. getServlet (). getServletContext (). getRealPath ("images"); // obtain the input stream InputStream in = file. getInputStream (); // defines the File input stream OutputStream fileout = new FileOutputStream (dir + File. separator + newfilename); int c = 0; byte [] buffer = new byte [1024]; while (c = in. read (buffer, 0, 1024 ))! =-1) {fileout. write (buffer, 0, c);} file. destroy (); // database record information Product pro = new Product (); pro. setProductname (addForm. getProductname (); pro. setImagespath (imagespath); biz. saveProduct (pro);} catch (Exception e) {e. printStackTrace ();} return null ;}
Jsp part:
1. add <% @ page language = "java" pageEncoding = "UTF-8" %> <% @ taglib uri = "http://jakarta.apache.org/struts/tags-bean" prefix = "bean" %> <% @ taglib uri =" http://jakarta.apache.org/struts/tags-html "prefix =" html "%> JSP for AddForm form
Product Name:
Product image:
2: Display