JSP上传显示图片

Apache commons-fileupload是一个很好的文件上传工具,最近使用commons-fileupload实现了图片的上传及显示,可将图片保存在指定的文件夹中,也可以将图片存放在数据库,并支持四种常用的图片格式:jpg,png,gif,bmp。

  首先,跟上传一般文件一样,需要写一个servlet来处理上传的文件,你可以修改保存路径或选择将图片保存在数据库中,只需要做简单的修改就行了,servlet代码如下:
FileUploadServlet.java
package com.ek.servlet;
import java.awt.image.BufferedImage;

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;
import javax.servlet.ServletException;

importjavax.servlet.http.HttpServlet;

importjavax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;

importorg.apache.commons.fileupload.FileUploadException;

importorg.apache.commons.fileupload.disk.DiskFileItemFactory;

import org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.ek.image.ImageUtil;
public class FileUploadServlet extends HttpServlet {
/**

*

*/

private static final long serialVersionUID = 1L;
private static String filePath = "";
/**

*Destructionoftheservlet.<br>

*/
public void destroy() {

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));
   ServletFileUpload upload = new ServletFileUpload(factory);

//maximumsizebeforeaFileUploadExceptionwillbethrown

upload.setSizeMax(1000000);

try{

    List fileItems = upload.parseRequest(req);
    Iterator iter = fileItems.iterator();
    // Get the file name    String regExp = ".+\\\\(.+\\.?())$";
    Pattern fileNamePattern = Pattern.compile(regExp);

while(iter.hasNext()){

     FileItem item = (FileItem) iter.next();
     if (!item.isFormField()) {

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);
        InputStream stream = item.getInputStream();

ByteArrayOutputStreambaos=newByteArrayOutputStream();

byte[]b=newbyte[1000];

while(stream.read(b)>0){

baos.write(b);

        }
        byte[] imageByte = baos.toByteArray();        String type = ImageUtil.getImageType(imageByte);
        if (type.equals(ImageUtil.TYPE_NOT_AVAILABLE))

thrownewException("fileisnotaimage");

BufferedImagemyImage=ImageUtil

          .readImage(imageByte);
        // display the image

ImageUtil.printImage(myImage,type,res

          .getOutputStream());
       // save the image

//ifyouwanttosavethefileintodatabase,doithere

//whenyouwanttodisplaytheimage,usethemethodprintImageinImageUtil

item.write(newFile(filePath+"\\"+m.group(1)));

stream.close();

        baos.close();
       } catch (Exception e) {

e.printStackTrace();

       }
      } else {

thrownewIOException("failtoupload");

}

}

}

}catch(IOExceptione){

e.printStackTrace();

}catch(FileUploadExceptione){

e.printStackTrace();

}

}
/**

*Initializationoftheservlet.<br>

*

*@throwsServletException

*ifanerroroccure

*/

publicvoidinit()throwsServletException{

//Changethefilepathhere

filePath=getServletContext().getRealPath("/");

}
}
  servlet中使用到一个ImageUtil类,其中封装了图片处理的实用方法,用于读写图片,代码如下:
ImageUtil.java
package com.ek.image;
import java.awt.Component;

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;
import javax.imageio.ImageIO;

importjavax.imageio.ImageReader;

import javax.imageio.stream.MemoryCacheImageInputStream;
import net.jmge.gif.Gif89Encoder;
import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;
import com.sun.imageio.plugins.bmp.BMPImageReader;

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

*/
public class ImageUtil {public static final String TYPE_GIF = "gif";
public static final String TYPE_JPEG = "jpeg";
public static final String TYPE_PNG = "png";
public static final String TYPE_BMP = "bmp";
public static final String TYPE_NOT_AVAILABLE = "na";
private static ColorModel getColorModel(Image image)

throwsInterruptedException,IllegalArgumentException{

PixelGrabberpg=newPixelGrabber(image,0,0,1,1,false);

if(!pg.grabPixels())

thrownewIllegalArgumentException();

returnpg.getColorModel();

}
private static void loadImage(Image image) throws InterruptedException,

IllegalArgumentException{

Componentdummy=newComponent(){

privatestaticfinallongserialVersionUID=1L;

};

MediaTrackertracker=newMediaTracker(dummy);

tracker.addImage(image,0);

tracker.waitForID(0);

if(tracker.isErrorID(0))

thrownewIllegalArgumentException();

}
public static BufferedImage createBufferedImage(Image image)

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;

}
public static BufferedImage readImage(InputStream is) {

BufferedImageimage=null;

try{

    image = ImageIO.read(is);
   } catch (IOException e) {

//TODOAuto-generatedcatchblock

e.printStackTrace();

}

returnimage;

}

publicstaticBufferedImagereadImage(byte[]imageByte){

ByteArrayInputStreambais=newByteArrayInputStream(imageByte);

BufferedImageimage=readImage(bais);

returnimage;

}
public static void encodeGIF(BufferedImage image, OutputStream out)    throws IOException {
   Gif89Encoder encoder = new Gif89Encoder(image);
   encoder.encode(out);}
/**

*

*@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;
   ByteArrayInputStream bais = null;   MemoryCacheImageInputStream mcis = null;
   try {

bais=newByteArrayInputStream(textObj);

    mcis = new MemoryCacheImageInputStream(bais);
    Iterator itr = ImageIO.getImageReaders(mcis);
    while (itr.hasNext()) {     ImageReader reader = (ImageReader) itr.next();
     if (reader instanceof GIFImageReader) {

type=TYPE_GIF;

}elseif(readerinstanceofJPEGImageReader){

type=TYPE_JPEG;

}elseif(readerinstanceofPNGImageReader){

type=TYPE_PNG;

}elseif(readerinstanceofBMPImageReader){

type=TYPE_BMP;

     }
     reader.dispose();

}

}finally{

if(bais!=null){

try{

bais.close();

}catch(IOExceptionioe){

if(_log.isWarnEnabled()){

_log.warn(ioe);

}

}

    }
    if (mcis != null) {

try{

mcis.close();

}catch(IOExceptionioe){

if(_log.isWarnEnabled()){

_log.warn(ioe);

}

}

}

   }
   if (_log.isDebugEnabled()) {

_log.debug("Detectedtype"+type);

   }
   return type;}
private static Log _log = LogFactory.getLog(ImageUtil.class);}
注意:对gif格式的图片进行处理的时候,需要另外一下jar包:gif89.jar,因为gif格式的图片不能使用ImageIO进行输出。
  如需将图片存放到数据库中,只需要修改红色部分,将图片以blob格式保存到数据库中,显示时以byte[]格式读出,使用ImageUtil.printImage()进行输出。

相关推荐