Jsp File Upload

Source: Internet
Author: User

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
$ {Product. productname}


Related Article

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.