1. To achieve the image upload, first need a component, here I use Smartupload.jar can download http://download.csdn.net/detail/mengdecike/8279247
2. After downloading, copy this file directly to Webcontent/web-inf/lib
3.jsp page
1<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "2pageencoding= "UTF-8"%>3<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "HTTP://WWW.W3.ORG/TR/HTML4/LOOSE.DTD" >456<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 ">7<title>insert title here</title>89<body>Ten<form action= "UpLoad" method= "post" enctype= "Multipart/form-data" Name= "Form1" > One<p>User name: A<label for= "username" ></label> -<input type= "text" name= "username" id= "username" > -</p> the<p>Avatar: -<label for= "Photo" ></label> -<input type= "file" name= "photo" id= "Photo" > -</p> +<p> -<input type= "Submit" name= "button" id= "button" value= "Submit" > +</p> A</form> at</body> -4. Upload the servlet code as follows:
1
Request.setcharacterencoding ("Utf-8");//Set character2Response.setcontenttype ("Text/html;charset=utf-8");3Response.setcharacterencoding ("Utf-8");4PrintWriter out =response.getwriter ();//Get Out Output object5 6 //prepare to upload directory7String Path = This. Getservletcontext (). Getrealpath ("Images");8File Fpath =NewFile (path);9 if(!fpath.exists ()) {Ten Fpath.mkdir (); One } A - //Instantiating Components -Smartupload su =NewSmartupload ("Utf-8"); the //Initializing Components -Su.initialize ( This. Getservletconfig (), request, response); - - Try { + //Limited -Su.setallowedfileslist ("Jpg,png,gif"); +Su.setmaxfilesize (50*1024);//cannot exceed 50K A at //uploading and extracting files - su.upload (); -Smartfile file = Su.getfiles (). GetFile (0); - //Generate file name -String fname =NewDate (). GetTime () + "." +File.getfileext (); - //Save File inFile.saveas (path+ "/" +fname); - //File.saveas (path+ "/" +fname,1); to //Tips +Out.println ("<script>alert (' File upload succeeded! '); location.href= ' upload.jsp ';</script> "); - the //extracting field information *String username = su.getrequest (). GetParameter ("username"); $System.out.println (">>>" +username);Panax Notoginseng - //Perform database operations the + A}Catch(SecurityException e) { theOut.println ("<script>alert (') can only upload jpg, PNG, GIF files and cannot exceed 50k! '); History.back ();</script> "); + e.printstacktrace (); - } $ Catch(smartuploadexception e) { $ //TODO auto-generated Catch block -Out.println ("<script>alert (' File upload failed! '); History.back ();</script> "); - e.printstacktrace (); the } -
If you need the entire full resource, you can download resources to http://download.csdn.net/detail/mengdecike/8279275.
JSP image upload