It is also a super simple method to use servlet to upload Image Code in jsp. If you need it, please refer to it.
| 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 ();
}
} |