---
title: "JSP上传显示图片代码（转）"
author: "sumongh"
date: "2007-07-10T18:41:32Z"
tags: []
slug: "jsp"
draft: false
lastmod: "2007-07-10T18:41:32Z"
id: 99854
url: "https://sumongh.iteye.com/blog/99854"
---

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

　　首先，跟上传一般文件一样，需要写一个servlet来处理上传的文件，你可以修改保存路径或选择将图片保存在数据库中，只需要做简单的修改就行了，servlet代码如下：

**FileUploadServlet.java**

java 代码

001. package com.ek.servlet;
002. import java.awt.image.BufferedImage;
003. import java.io.ByteArrayOutputStream;
004. import java.io.File;
005. import java.io.IOException;
006. import java.io.InputStream;
007. import java.util.Iterator;
008. import java.util.List;
009. import java.util.regex.Matcher;
010. import java.util.regex.Pattern;
011. import javax.servlet.ServletException;
012. import javax.servlet.http.HttpServlet;
013. import javax.servlet.http.HttpServletRequest;
014. import javax.servlet.http.HttpServletResponse;
015. import org.apache.commons.fileupload.FileItem;
016. import org.apache.commons.fileupload.FileUploadException;
017. import org.apache.commons.fileupload.disk.DiskFileItemFactory;
018. import org.apache.commons.fileupload.servlet.ServletFileUpload;
019. import com.ek.image.ImageUtil;
020. public class FileUploadServlet extends HttpServlet {
021. /\**
022. \*
023. \*/
024. private static final long serialVersionUID = 1L;
025. private static String filePath = "";
026. /\**
027. * Destruction of the servlet.
028. \*/
029. public void destroy() {
030. super.destroy(); // Just puts "destroy" string in log
031. // Put your code here
032. }
033. /\**
034. * The doPost method of the servlet.
035. \*
036. * This method is called when a form has its tag value method equals to
037. * post.
038. \*
039. * @param request
040. *            the request send by the client to the server
041. * @param response
042. *            the response send by the server to the client
043. * @throws ServletException
044. *             if an error occurred
045. * @throws IOException
046. *             if an error occurred
047. \*/
048. public void doPost(HttpServletRequest req, HttpServletResponse res)
049. throws ServletException, IOException {
050. res.setContentType("text/html; charset=UTF-8");
051. DiskFileItemFactory factory = new DiskFileItemFactory();
052. // maximum size that will be stored in memory
053. factory.setSizeThreshold(4096);
054. // the location for saving data that is larger than getSizeThreshold()
055. factory.setRepository(new File(filePath));
056. ServletFileUpload upload = new ServletFileUpload(factory);
057. // maximum size before a FileUploadException will be thrown
058. upload.setSizeMax(1000000);
059. try {
060. List fileItems = upload.parseRequest(req);
061. Iterator iter = fileItems.iterator();
062. // Get the file name
063. String regExp = ".+\\\\\\\\(.+\\\\.?())$";
064. Pattern fileNamePattern = Pattern.compile(regExp);
065. while (iter.hasNext()) {
066. FileItem item = (FileItem) iter.next();
067. if (!item.isFormField()) {
068. String name = item.getName();
069. long size = item.getSize();
070. if ((name == null || name.equals("")) && size == 0)
071. continue;
072. Matcher m = fileNamePattern.matcher(name);
073. boolean result = m.find();
074. if (result) {
075. try {
076. // String type =
077. // m.group(1).substring(m.group(1).lastIndexOf('.')+1);
078. InputStream stream = item.getInputStream();
079. ByteArrayOutputStream baos = new ByteArrayOutputStream();
080. byte\[] b = new byte\[1000];
081. while (stream.read(b) &gt; 0) {
082. baos.write(b);
083. }
084. byte\[] imageByte = baos.toByteArray();
085. String type = ImageUtil.getImageType(imageByte);
086. if (type.equals(ImageUtil.TYPE\_NOT\_AVAILABLE))
087. throw new Exception("file is not a image");
088. BufferedImage myImage = ImageUtil
089. .readImage(imageByte);
090. // display the image
091. ImageUtil.printImage(myImage, type, res
092. .getOutputStream());
093. // save the image
094. // if you want to save the file into database, do it here
095. // when you want to display the image, use the method printImage in ImageUtil
096. item.write(new File(filePath + "\\\\" + m.group(1)));
097. stream.close();
098. baos.close();
099. } catch (Exception e) {
100. e.printStackTrace();
101. }
102. } else {
103. throw new IOException("fail to upload");
104. }
105. }
106. }
107. } catch (IOException e) {
108. e.printStackTrace();
109. } catch (FileUploadException e) {
110. e.printStackTrace();
111. }
112. }
113. /\**
114. * Initialization of the servlet.
115. \*
116. * @throws ServletException
117. *             if an error occure
118. \*/
119. public void init() throws ServletException {
120. // Change the file path here
121. filePath = getServletContext().getRealPath("/");
122. }
123. }

servlet中使用到一个ImageUtil类，其中封装了图片处理的实用方法，用于读写图片，代码如下：

 

**ImageUtil.java**

java 代码

001. package com.ek.image;
002. import java.awt.Component;
003. import java.awt.Graphics2D;
004. import java.awt.GraphicsConfiguration;
005. import java.awt.GraphicsDevice;
006. import java.awt.GraphicsEnvironment;
007. import java.awt.Image;
008. import java.awt.MediaTracker;
009. import java.awt.image.BufferedImage;
010. import java.awt.image.ColorModel;
011. import java.awt.image.PixelGrabber;
012. import java.io.ByteArrayInputStream;
013. import java.io.IOException;
014. import java.io.InputStream;
015. import java.io.OutputStream;
016. import java.util.Iterator;
017. import javax.imageio.ImageIO;
018. import javax.imageio.ImageReader;
019. import javax.imageio.stream.MemoryCacheImageInputStream;
020. import net.jmge.gif.Gif89Encoder;
021. import org.apache.commons.logging.Log;
022. import org.apache.commons.logging.LogFactory;
023. import com.sun.imageio.plugins.bmp.BMPImageReader;
024. import com.sun.imageio.plugins.gif.GIFImageReader;
025. import com.sun.imageio.plugins.jpeg.JPEGImageReader;
026. import com.sun.imageio.plugins.png.PNGImageReader;
027. /\**
028. * @author Erick Kong
029. * @see ImageUtil.java
030. * @createDate: 2007-6-22
031. * @version 1.0
032. \*/
033. public class ImageUtil {
034. public static final String TYPE\_GIF = "gif";
035. public static final String TYPE\_JPEG = "jpeg";
036. public static final String TYPE\_PNG = "png";
037. public static final String TYPE\_BMP = "bmp";
038. public static final String TYPE\_NOT\_AVAILABLE = "na";
039. private static ColorModel getColorModel(Image image)
040. throws InterruptedException, IllegalArgumentException {
041. PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false);
042. if (!pg.grabPixels())
043. throw new IllegalArgumentException();
044. return pg.getColorModel();
045. }
046. private static void loadImage(Image image) throws InterruptedException,
047. IllegalArgumentException {
048. Component dummy = new Component() {
049. private static final long serialVersionUID = 1L;
050. };
051. MediaTracker tracker = new MediaTracker(dummy);
052. tracker.addImage(image, 0);
053. tracker.waitForID(0);
054. if (tracker.isErrorID(0))
055. throw new IllegalArgumentException();
056. }
057. public static BufferedImage createBufferedImage(Image image)
058. throws InterruptedException, IllegalArgumentException {
059. loadImage(image);
060. int w = image.getWidth(null);
061. int h = image.getHeight(null);
062. ColorModel cm = getColorModel(image);
063. GraphicsEnvironment ge = GraphicsEnvironment
064. .getLocalGraphicsEnvironment();
065. GraphicsDevice gd = ge.getDefaultScreenDevice();
066. GraphicsConfiguration gc = gd.getDefaultConfiguration();
067. BufferedImage bi = gc.createCompatibleImage(w, h, cm.getTransparency());
068. Graphics2D g = bi.createGraphics();
069. g.drawImage(image, 0, 0, null);
070. g.dispose();
071. return bi;
072. }
073. public static BufferedImage readImage(InputStream is) {
074. BufferedImage image = null;
075. try {
076. image = ImageIO.read(is);
077. } catch (IOException e) {
078. // TODO Auto-generated catch block
079. e.printStackTrace();
080. }
081. return image;
082. }
083. public static BufferedImage readImage(byte\[] imageByte) {
084. ByteArrayInputStream bais = new ByteArrayInputStream(imageByte);
085. BufferedImage image = readImage(bais);
086. return image;
087. }
088. public static void encodeGIF(BufferedImage image, OutputStream out)
089. throws IOException {
090. Gif89Encoder encoder = new Gif89Encoder(image);
091. encoder.encode(out);
092. }
093. /\**
094. \*
095. * @param bi
096. * @param type
097. * @param out
098. \*/
099. public static void printImage(BufferedImage bi, String type,
100. OutputStream out) {
101. try {
102. if (type.equals(TYPE\_GIF))
103. encodeGIF(bi, out);
104. else
105. ImageIO.write(bi, type, out);
106. } catch (IOException e) {
107. // TODO Auto-generated catch block
108. e.printStackTrace();
109. }
110. }
111. /\**
112. * Get image type from byte\[]
113. \*
114. * @param textObj
115. *            image byte\[]
116. * @return String image type
117. \*/
118. public static String getImageType(byte\[] textObj) {
119. String type = TYPE\_NOT\_AVAILABLE;
120. ByteArrayInputStream bais = null;
121. MemoryCacheImageInputStream mcis = null;
122. try {
123. bais = new ByteArrayInputStream(textObj);
124. mcis = new MemoryCacheImageInputStream(bais);
125. Iterator itr = ImageIO.getImageReaders(mcis);
126. while (itr.hasNext()) {
127. ImageReader reader = (ImageReader) itr.next();
128. if (reader instanceof GIFImageReader) {
129. type = TYPE\_GIF;
130. } else if (reader instanceof JPEGImageReader) {
131. type = TYPE\_JPEG;
132. } else if (reader instanceof PNGImageReader) {
133. type = TYPE\_PNG;
134. } else if (reader instanceof BMPImageReader) {
135. type = TYPE\_BMP;
136. }
137. reader.dispose();
138. }
139. } finally {
140. if (bais != null) {
141. try {
142. bais.close();
143. } catch (IOException ioe) {
144. if (\_log.isWarnEnabled()) {
145. \_log.warn(ioe);
146. }
147. }
148. }
149. if (mcis != null) {
150. try {
151. mcis.close();
152. } catch (IOException ioe) {
153. if (\_log.isWarnEnabled()) {
154. \_log.warn(ioe);
155. }
156. }
157. }
158. }
159. if (\_log.isDebugEnabled()) {
160. \_log.debug("Detected type " + type);
161. }
162. return type;
163. }
164. private static Log \_log = LogFactory.getLog(ImageUtil.class);
165. }

注意：对gif格式的图片进行处理的时候，需要另外一下jar包：gif89.jar，因为gif格式的图片不能使用ImageIO进行输出。

　　如需将图片存放到数据库中，只需要修改红色部分，将图片以blob格式保存到数据库中，显示时以byte\[]格式读出，使用ImageUtil.printImage()进行输出。