(30) Product Management-Add item (upload image)

Source: Internet
Author: User

Add Item (upload image)1Add a connection on the Modify page/store/adminproduct?method=Addui2. In Addui request forward to add page3. Modify the action on the form page:/store/Addproductservlet Submission Method: Method= "POST"Add enctype property: Enctype= "Multipart/form-data"Add the Name property to each field4. Addproductservlet information obtained through request.getparametermap all empty we want to use Beanuitls.populate (BEAN,MAP), we need to create a Map collection, the front desk to accept the information manually put into the map note: Pictures of the product:1: Save the disk to the server2To add a picture to the data, call Productservice to complete the Add product operation Redirect to all items above////////////////////////////////    ////////////////////////////////    ////////////////////////////////FileUpload using the Create a disk file entry factory Diskfileitemfactory factory=Newdiskfileitemfactory (); Create a core File upload object Servletfileupload servletfileupload upload=Newservletfileupload (Factory); Upload object Call method resolution request get a list<FileItem>List<FileItem> list =upload.parserequest (Request); Traverse list to get each file entry isformfiled (): Determine if it is a normal upload componenttrue: Normal upload componentfalse: File Upload Component Getfiledname (): Gets the Name property value of the form label if the normal upload component getString ("Utf-8"): Gets the value entered by the user if the file Upload Component GetName (): Gets the name of the uploaded file getInputStream (): Gets the upload file stream Finally delete temporary files delete ()
Importing the FileUpload jar package

Http://pan.baidu.com/s/1jIb11gq

/store/webcontent/admin/product/list.jsp

/store/src/com/louis/web/servlet/adminproductservlet.java
/*** Skip to the page where you added the item *@paramRequest *@paramResponse *@return     * @throwsException*/     PublicString Addui (httpservletrequest request, httpservletresponse response)throwsException {//query all categories to return to listCategoryservice cs= (Categoryservice) Beanfactory.getbean ("Categoryservice"); List<Category> CList =Cs.findall (); //put list in RequestRequest.setattribute ("CList", CList); return"/admin/product/add.jsp"; }
/store/webcontent/admin/product/add.jsp

/store/src/com/louis/web/servlet/addproductservlet.java
 PackageCom.louis.web.servlet;ImportJava.io.File;ImportJava.io.FileOutputStream;Importjava.io.IOException;ImportJava.io.InputStream;Importjava.util.Date;ImportJava.util.HashMap;Importjava.util.List;Importjavax.servlet.ServletException;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;Importorg.apache.commons.beanutils.BeanUtils;ImportOrg.apache.commons.fileupload.FileItem;Importorg.apache.commons.fileupload.disk.DiskFileItemFactory;ImportOrg.apache.commons.fileupload.servlet.ServletFileUpload;Importorg.apache.commons.io.IOUtils;Importcom.louis.domain.Category;Importcom.louis.domain.Product;ImportCom.louis.service.ProductService;Importcom.louis.utils.BeanFactory;Importcom.louis.utils.UUIDUtils;Importcom.louis.utils.UploadUtils;/*** Servlet Implementation class Addproduct*/ Public classAddproductservletextendsHttpServlet {protected voidDoget (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {Try {            //0. Create a map to put data into the foregroundhashmap<string, object> map =NewHashmap<>(); //Create a disk file entryDiskfileitemfactory factory =Newdiskfileitemfactory (); //creating a core upload objectServletfileupload upload =Newservletfileupload (Factory); //Parse Requestlist<fileitem> list =upload.parserequest (Request); //iterating through the collection             for(Fileitem fi:list) {//determine if it is an ordinary upload component                if(Fi.isformfield ()) {//Normal upload ComponentsMap.put (Fi.getfieldname (), fi.getstring ("Utf-8")); }Else{                    //File Upload Component//Get file nameString name =Fi.getname (); //gets the real name of the file xxxx.xxString realname =uploadutils.getrealname (name); //get the random name of a fileString Uuidname =Uploadutils.getuuidname (realname); //get the file's storage pathString Path = This. Getservletcontext (). Getrealpath ("/PRODUCTS/1"); //Get file StreamInputStream is =Fi.getinputstream (); //Save PictureFileOutputStream OS =NewFileOutputStream (NewFile (path, uuidname));                    Ioutils.copy (is, OS);                    Os.close ();                                        Is.close (); //Delete temporary filesFi.delete (); //set the path of a file in mapMap.put (Fi.getfieldname (), "products/1/" +uuidname); }                            }                                                //1. Package ParametersProduct p =NewProduct ();                        Beanutils.populate (P, map); //1.1 Product IDP.setpid (Uuidutils.getid ()); //1.2 Item TimeP.setpdate (NewDate ()); //1.3 Package CateogryCategory C =NewCategory (); C.setcid (String) map.get ("CID"));                        P.setcategory (c); //2. Call service to complete the addProductservice ps= (Productservice) Beanfactory.getbean ("Productservice");                        Ps.add (P); //3. Page RedirectionResponse.sendredirect (Request.getcontextpath () + "/adminproduct?method=findall"); } Catch(Exception e) {e.printstacktrace (); Request.setattribute ("MSG", "Product Add failed ~"); Request.getrequestdispatcher ("/jsp/msg.jsp"). Forward (request, response); return; }                    }    protected voidDoPost (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {//TODO auto-generated Method Stubdoget (request, response); }}

/store/webcontent/web-inf/web.xml
  <servlet>    <description></description>    <display-name>addproductservlet</ display-name>    <servlet-name>AddProductServlet</servlet-name>    <servlet-class >com.louis.web.servlet.addproductservlet</servlet-class>  </servlet>  < servlet-mapping>    <servlet-name>AddProductServlet</servlet-name>    <url-pattern>/ Addproduct</url-pattern>  </servlet-mapping>

Problem:

Beanutils

UploadFile

Map

(30) Product Management-Add item (upload image)

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.