ITeye博客

JSP上传显示图片代码(转)

sumongh · 2007-07-10 18:41 · 优秀代码收藏 · Markdown

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

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

FileUploadServlet.java

java 代码

  1. package com.ek.servlet;
  2. import java.awt.image.BufferedImage;
  3. import java.io.ByteArrayOutputStream;
  4. import java.io.File;
  5. import java.io.IOException;
  6. import java.io.InputStream;
  7. import java.util.Iterator;
  8. import java.util.List;
  9. import java.util.regex.Matcher;
  10. import java.util.regex.Pattern;
  11. import javax.servlet.ServletException;
  12. import javax.servlet.http.HttpServlet;
  13. import javax.servlet.http.HttpServletRequest;
  14. import javax.servlet.http.HttpServletResponse;
  15. import org.apache.commons.fileupload.FileItem;
  16. import org.apache.commons.fileupload.FileUploadException;
  17. import org.apache.commons.fileupload.disk.DiskFileItemFactory;
  18. import org.apache.commons.fileupload.servlet.ServletFileUpload;
  19. import com.ek.image.ImageUtil;
  20. public class FileUploadServlet extends HttpServlet {
  21. /**
  22. *
  23. */
  24. private static final long serialVersionUID = 1L;
  25. private static String filePath = "";
  26. /**
  27. * Destruction of the servlet.
  28. */
  29. public void destroy() {
  30. super.destroy(); // Just puts "destroy" string in log
  31. // Put your code here
  32. }
  33. /**
  34. * The doPost method of the servlet.
  35. *
  36. * This method is called when a form has its tag value method equals to
  37. * post.
  38. *
  39. * @param request
  40. *            the request send by the client to the server
  41. * @param response
  42. *            the response send by the server to the client
  43. * @throws ServletException
  44. *             if an error occurred
  45. * @throws IOException
  46. *             if an error occurred
  47. */
  48. public void doPost(HttpServletRequest req, HttpServletResponse res)
  49. throws ServletException, IOException {
  50. res.setContentType("text/html; charset=UTF-8");
  51. DiskFileItemFactory factory = new DiskFileItemFactory();
  52. // maximum size that will be stored in memory
  53. factory.setSizeThreshold(4096);
  54. // the location for saving data that is larger than getSizeThreshold()
  55. factory.setRepository(new File(filePath));
  56. ServletFileUpload upload = new ServletFileUpload(factory);
  57. // maximum size before a FileUploadException will be thrown
  58. upload.setSizeMax(1000000);
  59. try {
  60. List fileItems = upload.parseRequest(req);
  61. Iterator iter = fileItems.iterator();
  62. // Get the file name
  63. String regExp = ".+\\\\(.+\\.?())$";
  64. Pattern fileNamePattern = Pattern.compile(regExp);
  65. while (iter.hasNext()) {
  66. FileItem item = (FileItem) iter.next();
  67. if (!item.isFormField()) {
  68. String name = item.getName();
  69. long size = item.getSize();
  70. if ((name == null || name.equals("")) && size == 0)
  71. continue;
  72. Matcher m = fileNamePattern.matcher(name);
  73. boolean result = m.find();
  74. if (result) {
  75. try {
  76. // String type =
  77. // m.group(1).substring(m.group(1).lastIndexOf('.')+1);
  78. InputStream stream = item.getInputStream();
  79. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  80. byte[] b = new byte[1000];
  81. while (stream.read(b) > 0) {
  82. baos.write(b);
  83. }
  84. byte[] imageByte = baos.toByteArray();
  85. String type = ImageUtil.getImageType(imageByte);
  86. if (type.equals(ImageUtil.TYPE_NOT_AVAILABLE))
  87. throw new Exception("file is not a image");
  88. BufferedImage myImage = ImageUtil
  89. .readImage(imageByte);
  90. // display the image
  91. ImageUtil.printImage(myImage, type, res
  92. .getOutputStream());
  93. // save the image
  94. // if you want to save the file into database, do it here
  95. // when you want to display the image, use the method printImage in ImageUtil
  96. item.write(new File(filePath + "\\" + m.group(1)));
  97. stream.close();
  98. baos.close();
  99. } 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 代码

  1. package com.ek.image;
  2. import java.awt.Component;
  3. import java.awt.Graphics2D;
  4. import java.awt.GraphicsConfiguration;
  5. import java.awt.GraphicsDevice;
  6. import java.awt.GraphicsEnvironment;
  7. import java.awt.Image;
  8. import java.awt.MediaTracker;
  9. import java.awt.image.BufferedImage;
  10. import java.awt.image.ColorModel;
  11. import java.awt.image.PixelGrabber;
  12. import java.io.ByteArrayInputStream;
  13. import java.io.IOException;
  14. import java.io.InputStream;
  15. import java.io.OutputStream;
  16. import java.util.Iterator;
  17. import javax.imageio.ImageIO;
  18. import javax.imageio.ImageReader;
  19. import javax.imageio.stream.MemoryCacheImageInputStream;
  20. import net.jmge.gif.Gif89Encoder;
  21. import org.apache.commons.logging.Log;
  22. import org.apache.commons.logging.LogFactory;
  23. import com.sun.imageio.plugins.bmp.BMPImageReader;
  24. import com.sun.imageio.plugins.gif.GIFImageReader;
  25. import com.sun.imageio.plugins.jpeg.JPEGImageReader;
  26. import com.sun.imageio.plugins.png.PNGImageReader;
  27. /**
  28. * @author Erick Kong
  29. * @see ImageUtil.java
  30. * @createDate: 2007-6-22
  31. * @version 1.0
  32. */
  33. public class ImageUtil {
  34. public static final String TYPE_GIF = "gif";
  35. public static final String TYPE_JPEG = "jpeg";
  36. public static final String TYPE_PNG = "png";
  37. public static final String TYPE_BMP = "bmp";
  38. public static final String TYPE_NOT_AVAILABLE = "na";
  39. private static ColorModel getColorModel(Image image)
  40. throws InterruptedException, IllegalArgumentException {
  41. PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false);
  42. if (!pg.grabPixels())
  43. throw new IllegalArgumentException();
  44. return pg.getColorModel();
  45. }
  46. private static void loadImage(Image image) throws InterruptedException,
  47. IllegalArgumentException {
  48. Component dummy = new Component() {
  49. private static final long serialVersionUID = 1L;
  50. };
  51. MediaTracker tracker = new MediaTracker(dummy);
  52. tracker.addImage(image, 0);
  53. tracker.waitForID(0);
  54. if (tracker.isErrorID(0))
  55. throw new IllegalArgumentException();
  56. }
  57. public static BufferedImage createBufferedImage(Image image)
  58. throws InterruptedException, IllegalArgumentException {
  59. loadImage(image);
  60. int w = image.getWidth(null);
  61. int h = image.getHeight(null);
  62. ColorModel cm = getColorModel(image);
  63. GraphicsEnvironment ge = GraphicsEnvironment
  64. .getLocalGraphicsEnvironment();
  65. GraphicsDevice gd = ge.getDefaultScreenDevice();
  66. GraphicsConfiguration gc = gd.getDefaultConfiguration();
  67. BufferedImage bi = gc.createCompatibleImage(w, h, cm.getTransparency());
  68. Graphics2D g = bi.createGraphics();
  69. g.drawImage(image, 0, 0, null);
  70. g.dispose();
  71. return bi;
  72. }
  73. public static BufferedImage readImage(InputStream is) {
  74. BufferedImage image = null;
  75. try {
  76. image = ImageIO.read(is);
  77. } catch (IOException e) {
  78. // TODO Auto-generated catch block
  79. e.printStackTrace();
  80. }
  81. return image;
  82. }
  83. public static BufferedImage readImage(byte[] imageByte) {
  84. ByteArrayInputStream bais = new ByteArrayInputStream(imageByte);
  85. BufferedImage image = readImage(bais);
  86. return image;
  87. }
  88. public static void encodeGIF(BufferedImage image, OutputStream out)
  89. throws IOException {
  90. Gif89Encoder encoder = new Gif89Encoder(image);
  91. encoder.encode(out);
  92. }
  93. /**
  94. *
  95. * @param bi
  96. * @param type
  97. * @param out
  98. */
  99. 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()进行输出。

评论(5)

  1. #5 楼 · zuowangxi · 2009-09-06 10:41

    geeksun writes:

    import net.jmge.gif.Gif89Encoder;
    Gif89Encoder 这个类没贴出来

    确实。

  2. #4 楼 · zuowangxi · 2009-09-06 10:40

    Gif89Encoder 这个类在哪里呀? 我想要运行下你的代码都不行啊、、、、

  3. #3 楼 · nannancya · 2009-07-22 20:34

    :D :oops: :cry: 8) 8) ****

  4. #2 楼 · geeksun · 2009-01-14 15:21

    import net.jmge.gif.Gif89Encoder;
    Gif89Encoder 这个类没贴出来

  5. #1 楼 · lsk · 2007-12-18 09:45

    非常好.这种判断比用后缀名判断好多了. 顶楼主一下.

评论功能维护中,当前仅展示历史评论。