JSP上传显示图片
Apache commons-fileupload是一个很好的文件上传工具,最近使用commons-fileupload实现了图片的上传及显示,可将图片保存在指定的文件夹中,也可以将图片存放在数据库,并支持四种常用的图片格式:jpg,png,gif,bmp。
importjava.io.ByteArrayOutputStream;
importjava.io.File;
importjava.io.IOException;
importjava.io.InputStream;
importjava.util.Iterator;
importjava.util.List;
importjava.util.regex.Matcher;
import java.util.regex.Pattern;importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;importorg.apache.commons.fileupload.FileUploadException;
importorg.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;*
*/
private static final long serialVersionUID = 1L;*Destructionoftheservlet.<br>
*/super.destroy();//Justputs"destroy"stringinlog
//Putyourcodehere
}*ThedoPostmethodoftheservlet.<br>
*
*Thismethodiscalledwhenaformhasitstagvaluemethodequalsto
*post.
*
*@paramrequest
*therequestsendbytheclienttotheserver
*@paramresponse
*theresponsesendbytheservertotheclient
*@throwsServletException
*ifanerroroccurred
*@throwsIOException
*ifanerroroccurred
*/
publicvoiddoPost(HttpServletRequestreq,HttpServletResponseres)
throwsServletException,IOException{
res.setContentType("text/html;charset=UTF-8");
DiskFileItemFactoryfactory=newDiskFileItemFactory();
//maximumsizethatwillbestoredinmemory
factory.setSizeThreshold(4096);
//thelocationforsavingdatathatislargerthangetSizeThreshold()
factory.setRepository(new File(filePath));//maximumsizebeforeaFileUploadExceptionwillbethrown
upload.setSizeMax(1000000);
try{
List fileItems = upload.parseRequest(req);while(iter.hasNext()){
FileItem item = (FileItem) iter.next();Stringname=item.getName();
longsize=item.getSize();
if((name==null||name.equals(""))&&size==0)
continue;
Matcherm=fileNamePattern.matcher(name);
booleanresult=m.find();
if(result){
try{
//Stringtype=
// m.group(1).substring(m.group(1).lastIndexOf('.')+1);ByteArrayOutputStreambaos=newByteArrayOutputStream();
byte[]b=newbyte[1000];
while(stream.read(b)>0){
baos.write(b);
}thrownewException("fileisnotaimage");
BufferedImagemyImage=ImageUtil
.readImage(imageByte);ImageUtil.printImage(myImage,type,res
.getOutputStream());//ifyouwanttosavethefileintodatabase,doithere
//whenyouwanttodisplaytheimage,usethemethodprintImageinImageUtil
item.write(newFile(filePath+"\\"+m.group(1)));
stream.close();
baos.close();e.printStackTrace();
}thrownewIOException("failtoupload");
}
}
}
}catch(IOExceptione){
e.printStackTrace();
}catch(FileUploadExceptione){
e.printStackTrace();
}
}*Initializationoftheservlet.<br>
*
*@throwsServletException
*ifanerroroccure
*/
publicvoidinit()throwsServletException{
//Changethefilepathhere
filePath=getServletContext().getRealPath("/");
}importjava.awt.Graphics2D;
importjava.awt.GraphicsConfiguration;
importjava.awt.GraphicsDevice;
importjava.awt.GraphicsEnvironment;
importjava.awt.Image;
importjava.awt.MediaTracker;
importjava.awt.image.BufferedImage;
importjava.awt.image.ColorModel;
importjava.awt.image.PixelGrabber;
importjava.io.ByteArrayInputStream;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.OutputStream;
import java.util.Iterator;importjavax.imageio.ImageReader;
import javax.imageio.stream.MemoryCacheImageInputStream;importcom.sun.imageio.plugins.gif.GIFImageReader;
importcom.sun.imageio.plugins.jpeg.JPEGImageReader;
import com.sun.imageio.plugins.png.PNGImageReader;*@authorErickKong
*@seeImageUtil.java
*@createDate:2007-6-22
*@version1.0
*/throwsInterruptedException,IllegalArgumentException{
PixelGrabberpg=newPixelGrabber(image,0,0,1,1,false);
if(!pg.grabPixels())
thrownewIllegalArgumentException();
returnpg.getColorModel();
}IllegalArgumentException{
Componentdummy=newComponent(){
privatestaticfinallongserialVersionUID=1L;
};
MediaTrackertracker=newMediaTracker(dummy);
tracker.addImage(image,0);
tracker.waitForID(0);
if(tracker.isErrorID(0))
thrownewIllegalArgumentException();
}throwsInterruptedException,IllegalArgumentException{
loadImage(image);
intw=image.getWidth(null);
inth=image.getHeight(null);
ColorModelcm=getColorModel(image);
GraphicsEnvironmentge=GraphicsEnvironment
.getLocalGraphicsEnvironment();
GraphicsDevicegd=ge.getDefaultScreenDevice();
GraphicsConfigurationgc=gd.getDefaultConfiguration();
BufferedImagebi=gc.createCompatibleImage(w,h,cm.getTransparency());
Graphics2Dg=bi.createGraphics();
g.drawImage(image,0,0,null);
g.dispose();
returnbi;
}BufferedImageimage=null;
try{
image = ImageIO.read(is);//TODOAuto-generatedcatchblock
e.printStackTrace();
}
returnimage;
}
publicstaticBufferedImagereadImage(byte[]imageByte){
ByteArrayInputStreambais=newByteArrayInputStream(imageByte);
BufferedImageimage=readImage(bais);
returnimage;
}*
*@parambi
*@paramtype
*@paramout
*/
publicstaticvoidprintImage(BufferedImagebi,Stringtype,
OutputStreamout){
try{
if(type.equals(TYPE_GIF))
encodeGIF(bi,out);
else
ImageIO.write(bi,type,out);
}catch(IOExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}*Getimagetypefrombyte[]
*
*@paramtextObj
*imagebyte[]
*@returnStringimagetype
*/
publicstaticStringgetImageType(byte[]textObj){
String type = TYPE_NOT_AVAILABLE;bais=newByteArrayInputStream(textObj);
mcis = new MemoryCacheImageInputStream(bais);type=TYPE_GIF;
}elseif(readerinstanceofJPEGImageReader){
type=TYPE_JPEG;
}elseif(readerinstanceofPNGImageReader){
type=TYPE_PNG;
}elseif(readerinstanceofBMPImageReader){
type=TYPE_BMP;
}}
}finally{
if(bais!=null){
try{
bais.close();
}catch(IOExceptionioe){
if(_log.isWarnEnabled()){
_log.warn(ioe);
}
}
}try{
mcis.close();
}catch(IOExceptionioe){
if(_log.isWarnEnabled()){
_log.warn(ioe);
}
}
}
}_log.debug("Detectedtype"+type);
}