Apache commons-fileupload是一个很好的文件上传工具,最近使用commons-fileupload实现了图片的上传及显示,可将图片保存在指定的文件夹中,也可以将图片存放在数据库,并支持四种常用的图片格式:jpg,png,gif,bmp。
首先,跟上传一般文件一样,需要写一个servlet来处理上传的文件,你可以修改保存路径或选择将图片保存在数据库中,只需要做简单的修改就行了,servlet代码如下:
FileUploadServlet.java
package com.ek.servlet;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.FileUploadException;
import org.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 final long serialVersionUID = 1L;
private static String filePath = "";
/**
* Destruction of the servlet. <br>
*/
* Destruction of the servlet. <br>
*/
public void destroy() {
?? super.destroy(); // Just puts "destroy" string in log
?? // Put your code here
}
?? super.destroy(); // Just puts "destroy" string in log
?? // Put your code here
}
/**
* The doPost method of the servlet. <br>
*?
* This method is called when a form has its tag value method equals to
* post.
*?
* @param request
*??????????? the request send by the client to the server
* @param response
*??????????? the response send by the server to the client
* @throws ServletException
*???????????? if an error occurred
* @throws IOException
*???????????? if an error occurred
*/
public void doPost(HttpServletRequest req, HttpServletResponse res)
??? throws ServletException, IOException {
?? res.setContentType("text/html; charset=UTF-8");
?? DiskFileItemFactory factory = new DiskFileItemFactory();
?? // maximum size that will be stored in memory
?? factory.setSizeThreshold(4096);
?? // the location for saving data that is larger than getSizeThreshold()
?? factory.setRepository(new File(filePath));
* The doPost method of the servlet. <br>
*?
* This method is called when a form has its tag value method equals to
* post.
*?
* @param request
*??????????? the request send by the client to the server
* @param response
*??????????? the response send by the server to the client
* @throws ServletException
*???????????? if an error occurred
* @throws IOException
*???????????? if an error occurred
*/
public void doPost(HttpServletRequest req, HttpServletResponse res)
??? throws ServletException, IOException {
?? res.setContentType("text/html; charset=UTF-8");
?? DiskFileItemFactory factory = new DiskFileItemFactory();
?? // maximum size that will be stored in memory
?? factory.setSizeThreshold(4096);
?? // the location for saving data that is larger than getSizeThreshold()
?? factory.setRepository(new File(filePath));
?? ServletFileUpload upload = new ServletFileUpload(factory);
?? // maximum size before a FileUploadException will be thrown
?? upload.setSizeMax(1000000);
?? try {
??? List fileItems = upload.parseRequest(req);
?? // maximum size before a FileUploadException will be thrown
?? upload.setSizeMax(1000000);
?? try {
??? List fileItems = upload.parseRequest(req);
??? Iterator iter = fileItems.iterator();
??? // Get the file name
??? String regExp = ".+\\\\(.+\\.?())$";
??? String regExp = ".+\\\\(.+\\.?())$";
??? Pattern fileNamePattern = Pattern.compile(regExp);
??? while (iter.hasNext()) {
???? FileItem item = (FileItem) iter.next();
??? while (iter.hasNext()) {
???? FileItem item = (FileItem) iter.next();
???? if (!item.isFormField()) {
????? String name = item.getName();
????? long size = item.getSize();
????? if ((name == null || name.equals("")) && size == 0)
?????? continue;
????? Matcher m = fileNamePattern.matcher(name);
????? boolean result = m.find();
????? if (result) {
?????? try {
??????? // String type =
??????? // m.group(1).substring(m.group(1).lastIndexOf('.')+1);
????? String name = item.getName();
????? long size = item.getSize();
????? if ((name == null || name.equals("")) && size == 0)
?????? continue;
????? Matcher m = fileNamePattern.matcher(name);
????? boolean result = m.find();
????? if (result) {
?????? try {
??????? // String type =
??????? // m.group(1).substring(m.group(1).lastIndexOf('.')+1);
??????? InputStream stream = item.getInputStream();
??????? ByteArrayOutputStream baos = new ByteArrayOutputStream();
??????? byte[] b = new byte[1000];
??????? while (stream.read(b) > 0) {
???????? baos.write(b);
??????? }
??????? ByteArrayOutputStream baos = new ByteArrayOutputStream();
??????? byte[] b = new byte[1000];
??????? while (stream.read(b) > 0) {
???????? baos.write(b);
??????? }
??????? byte[] imageByte = baos.toByteArray();
??????? String type = ImageUtil.getImageType(imageByte);
??????? String type = ImageUtil.getImageType(imageByte);
??????? if (type.equals(ImageUtil.TYPE_NOT_AVAILABLE))
???????? throw new Exception("file is not a image");
??????? BufferedImage myImage = ImageUtil
????????? .readImage(imageByte);
???????? throw new Exception("file is not a image");
??????? BufferedImage myImage = ImageUtil
????????? .readImage(imageByte);
??????? // display the image
??????? ImageUtil.printImage(myImage, type, res
????????? .getOutputStream());
??????? ImageUtil.printImage(myImage, type, res
????????? .getOutputStream());
???????// save the image
??????? // if you want to save the file into database, do it here
??????? // when you want to display the image, use the method printImage in ImageUtil?
??????? item.write(new File(filePath + "\\" + m.group(1)));
???????
??????? stream.close();
??????? baos.close();
??????? // if you want to save the file into database, do it here
??????? // when you want to display the image, use the method printImage in ImageUtil?
??????? item.write(new File(filePath + "\\" + m.group(1)));
???????
??????? stream.close();
??????? baos.close();
?????? } catch (Exception e) {
??????? e.printStackTrace();
?????? }
??????? e.printStackTrace();
?????? }
????? } else {
?????? throw new IOException("fail to upload");
????? }
???? }
??? }
?? } catch (IOException e) {
??? e.printStackTrace();
?? } catch (FileUploadException e) {
??? e.printStackTrace();
?? }
}
?????? throw new IOException("fail to upload");
????? }
???? }
??? }
?? } catch (IOException e) {
??? e.printStackTrace();
?? } catch (FileUploadException e) {
??? e.printStackTrace();
?? }
}
/**
* Initialization of the servlet. <br>
*?
* @throws ServletException
*???????????? if an error occure
*/
public void init() throws ServletException {
?? // Change the file path here
?? filePath = getServletContext().getRealPath("/");
}
* Initialization of the servlet. <br>
*?
* @throws ServletException
*???????????? if an error occure
*/
public void init() throws ServletException {
?? // Change the file path here
?? filePath = getServletContext().getRealPath("/");
}
}
servlet中使用到一个ImageUtil类,其中封装了图片处理的实用方法,用于读写图片,代码如下:
ImageUtil.java
package com.ek.image;
import java.awt.Component;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.PixelGrabber;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.PixelGrabber;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.MemoryCacheImageInputStream;
import javax.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 org.apache.commons.logging.LogFactory;
import com.sun.imageio.plugins.bmp.BMPImageReader;
import com.sun.imageio.plugins.gif.GIFImageReader;
import com.sun.imageio.plugins.jpeg.JPEGImageReader;
import com.sun.imageio.plugins.png.PNGImageReader;
import com.sun.imageio.plugins.gif.GIFImageReader;
import com.sun.imageio.plugins.jpeg.JPEGImageReader;
import com.sun.imageio.plugins.png.PNGImageReader;
/**
* @author Erick Kong
* @see ImageUtil.java
* @createDate: 2007-6-22
* @version 1.0
*/
* @author Erick Kong
* @see ImageUtil.java
* @createDate: 2007-6-22
* @version 1.0
*/
public class ImageUtil {
public static final String TYPE_GIF = "gif";
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)
??? throws InterruptedException, IllegalArgumentException {
?? PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false);
?? if (!pg.grabPixels())
??? throw new IllegalArgumentException();
?? return pg.getColorModel();
}
??? throws InterruptedException, IllegalArgumentException {
?? PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false);
?? if (!pg.grabPixels())
??? throw new IllegalArgumentException();
?? return pg.getColorModel();
}
private static void loadImage(Image image) throws InterruptedException,
??? IllegalArgumentException {
?? Component dummy = new Component() {
??? private static final long serialVersionUID = 1L;
?? };
?? MediaTracker tracker = new MediaTracker(dummy);
?? tracker.addImage(image, 0);
?? tracker.waitForID(0);
?? if (tracker.isErrorID(0))
??? throw new IllegalArgumentException();
}
??? IllegalArgumentException {
?? Component dummy = new Component() {
??? private static final long serialVersionUID = 1L;
?? };
?? MediaTracker tracker = new MediaTracker(dummy);
?? tracker.addImage(image, 0);
?? tracker.waitForID(0);
?? if (tracker.isErrorID(0))
??? throw new IllegalArgumentException();
}
public static BufferedImage createBufferedImage(Image image)
??? throws InterruptedException, IllegalArgumentException {
?? loadImage(image);
?? int w = image.getWidth(null);
?? int h = image.getHeight(null);
?? ColorModel cm = getColorModel(image);
?? GraphicsEnvironment ge = GraphicsEnvironment
???? .getLocalGraphicsEnvironment();
?? GraphicsDevice gd = ge.getDefaultScreenDevice();
?? GraphicsConfiguration gc = gd.getDefaultConfiguration();
?? BufferedImage bi = gc.createCompatibleImage(w, h, cm.getTransparency());
?? Graphics2D g = bi.createGraphics();
?? g.drawImage(image, 0, 0, null);
?? g.dispose();
?? return bi;
}
??? throws InterruptedException, IllegalArgumentException {
?? loadImage(image);
?? int w = image.getWidth(null);
?? int h = image.getHeight(null);
?? ColorModel cm = getColorModel(image);
?? GraphicsEnvironment ge = GraphicsEnvironment
???? .getLocalGraphicsEnvironment();
?? GraphicsDevice gd = ge.getDefaultScreenDevice();
?? GraphicsConfiguration gc = gd.getDefaultConfiguration();
?? BufferedImage bi = gc.createCompatibleImage(w, h, cm.getTransparency());
?? Graphics2D g = bi.createGraphics();
?? g.drawImage(image, 0, 0, null);
?? g.dispose();
?? return bi;
}
public static BufferedImage readImage(InputStream is) {
?? BufferedImage image = null;
?? try {
??? image = ImageIO.read(is);
?? BufferedImage image = null;
?? try {
??? image = ImageIO.read(is);
?? } catch (IOException e) {
??? // TODO Auto-generated catch block
??? e.printStackTrace();
?? }
?? return image;
}
public static BufferedImage readImage(byte[] imageByte) {
?? ByteArrayInputStream bais = new ByteArrayInputStream(imageByte);
?? BufferedImage image = readImage(bais);
?? return image;
}
??? // TODO Auto-generated catch block
??? e.printStackTrace();
?? }
?? return image;
}
public static BufferedImage readImage(byte[] imageByte) {
?? ByteArrayInputStream bais = new ByteArrayInputStream(imageByte);
?? BufferedImage image = readImage(bais);
?? return image;
}
public static void encodeGIF(BufferedImage image, OutputStream out)
??? throws IOException {
??? throws IOException {
?? Gif89Encoder encoder = new Gif89Encoder(image);
?? encoder.encode(out);
}
}
/**
*?
* @param bi
* @param type
* @param out
*/
public static void printImage(BufferedImage bi, String type,
??? OutputStream out) {
?? try {
??? if (type.equals(TYPE_GIF))
???? encodeGIF(bi, out);
??? else
???? ImageIO.write(bi, type, out);
?? } catch (IOException e) {
??? // TODO Auto-generated catch block
??? e.printStackTrace();
?? }
}
*?
* @param bi
* @param type
* @param out
*/
public static void printImage(BufferedImage bi, String type,
??? OutputStream out) {
?? try {
??? if (type.equals(TYPE_GIF))
???? encodeGIF(bi, out);
??? else
???? ImageIO.write(bi, type, out);
?? } catch (IOException e) {
??? // TODO Auto-generated catch block
??? e.printStackTrace();
?? }
}
/**
* Get image type from byte[]
*?
* @param textObj
*??????????? image byte[]
* @return String image type
*/
public static String getImageType(byte[] textObj) {
?? String type = TYPE_NOT_AVAILABLE;
* Get image type from byte[]
*?
* @param textObj
*??????????? image byte[]
* @return String image type
*/
public static String getImageType(byte[] textObj) {
?? String type = TYPE_NOT_AVAILABLE;
?? ByteArrayInputStream bais = null;
?? MemoryCacheImageInputStream mcis = null;
?? MemoryCacheImageInputStream mcis = null;
?? try {
??? bais = new ByteArrayInputStream(textObj);
??? mcis = new MemoryCacheImageInputStream(bais);
??? bais = new ByteArrayInputStream(textObj);
??? mcis = new MemoryCacheImageInputStream(bais);
??? Iterator itr = ImageIO.getImageReaders(mcis);
??? while (itr.hasNext()) {
???? ImageReader reader = (ImageReader) itr.next();
???? ImageReader reader = (ImageReader) itr.next();
???? if (reader instanceof GIFImageReader) {
????? type = TYPE_GIF;
???? } else if (reader instanceof JPEGImageReader) {
????? type = TYPE_JPEG;
???? } else if (reader instanceof PNGImageReader) {
????? type = TYPE_PNG;
???? } else if (reader instanceof BMPImageReader) {
????? type = TYPE_BMP;
???? }
????? type = TYPE_GIF;
???? } else if (reader instanceof JPEGImageReader) {
????? type = TYPE_JPEG;
???? } else if (reader instanceof PNGImageReader) {
????? type = TYPE_PNG;
???? } else if (reader instanceof BMPImageReader) {
????? type = TYPE_BMP;
???? }
???? reader.dispose();
??? }
?? } finally {
??? if (bais != null) {
???? try {
????? bais.close();
???? } catch (IOException ioe) {
????? if (_log.isWarnEnabled()) {
?????? _log.warn(ioe);
????? }
???? }
??? }
??? }
?? } finally {
??? if (bais != null) {
???? try {
????? bais.close();
???? } catch (IOException ioe) {
????? if (_log.isWarnEnabled()) {
?????? _log.warn(ioe);
????? }
???? }
??? }
??? if (mcis != null) {
???? try {
????? mcis.close();
???? } catch (IOException ioe) {
????? if (_log.isWarnEnabled()) {
?????? _log.warn(ioe);
????? }
???? }
??? }
?? }
???? try {
????? mcis.close();
???? } catch (IOException ioe) {
????? if (_log.isWarnEnabled()) {
?????? _log.warn(ioe);
????? }
???? }
??? }
?? }
?? if (_log.isDebugEnabled()) {
??? _log.debug("Detected type " + type);
?? }
??? _log.debug("Detected type " + type);
?? }
?? return type;
}
}
private static Log _log = LogFactory.getLog(ImageUtil.class);
}
}
注意:对gif格式的图片进行处理的时候,需要另外一下jar包:gif89.jar,因为gif格式的图片不能使用ImageIO进行输出。
如需将图片存放到数据库中,只需要修改红色部分,将图片以blob格式保存到数据库中,显示时以byte[]格式读出,使用ImageUtil.printImage()进行输出。