Use servlet to upload images in jsp

Source: Internet
Author: User
The code is as follows: Copy code

First, the following components are required in JSP:

<H2 class = "h2">
Upload photo:
</H2>
<Form action = "pic. do" method = "post"
Enctype = "multipart/form-data">
<Input type = "file" name = "file1"/>
<Input type = "submit" value = "upload"/>
</Form>

Then, you can use the following code in the servlet to upload files:

If (path. equals ("/pic ")){

// Obtain the login user id, used to create a new folder and store the file s uploaded by the user
HttpSession session = request. getSession ();
User user = (User) session. getAttribute ("user ");
Long id = user. getId ();
   
DiskFileItemFactory factory = new DiskFileItemFactory ();
ServletFileUpload sfu = new ServletFileUpload (factory );
Try {
List <FileItem> items = sfu. parseRequest (request );
For (int I = 0; I <items. size (); I ++ ){
FileItem item = items. get (I );
If (item. isFormField ()){
String name = item. getString ();
System. out. println ("name" + name );
      }
Else {
ServletContext context = getServletContext ();
Path = context. getRealPath ("upload ");
File file = new File (path + "\ pic _" + id );
File. mkdir ();
      
String fileName1 = item. getName ();
String fileName = fileName1.substring (fileName1.lastIndexOf ("\") + 1 );
File = new File (path + "\" + "pic _" + id + "\" + fileName );
      
Item. write (file );
      }
     }
} Catch (Exception e ){
// TODO Auto-generated catch block
E. printStackTrace ();
    }
   
   }

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.