jsp_上传图片_代码
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 ImageU
til
96. item.write(new File(filePath + "\\" + m.group(1))); 97.
98. stream.close();
99. baos.close();
100. } catch (Exception e) {
101. e.printStackTrace();
102. }
103. } else {
104. throw new IOException("fail to upload"); 105. }
106. }
107. }
108. } catch (IOException e) {
109. e.printStackTrace();
110. } catch (FileUploadException e) {
111. e.printStackTrace();
112. }
113. }
114. /**
115. * Initialization of the servlet.
116. *
117. * @throws ServletException
118. * if an error occure 119. */
120. public void init() throws ServletException { 121. // Change the file path here 122. filePath = getServletContext().getRealPath("/");
123. }
124. }
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.
35. public static final String TYPE_GIF = "gif"; 36. public static final String TYPE_JPEG = "jpeg"; 37. public static final String TYPE_PNG = "png"; 38. public static final String TYPE_BMP = "bmp"; 39. public static final String TYPE_NOT_AVAILABLE = "na"; 40. private static ColorModel getColorModel(Image image) 41. throws InterruptedException, IllegalArgumentException {
42. PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false); 43. if (!pg.grabPixels())
44. throw new IllegalArgumentException();
45. return pg.getColorModel();
46. }
47. private static void loadImage(Image image) throws InterruptedException,
48. IllegalArgumentException {
49. Component dummy = new Component() {
50. private static final long serialVersionUID = 1L; 51. };
52. MediaTracker tracker = new MediaTracker(dummy); 53. tracker.addImage(image, 0);
54. tracker.waitForID(0);
55. if (tracker.isErrorID(0))
56. throw new IllegalArgumentException();
57. }
58. public static BufferedImage createBufferedImage(Image image) 59. throws InterruptedException, IllegalArgumentException { 60. loadImage(image);
61. int w = image.getWidth(null);
62. int h = image.getHeight(null);
63. ColorModel cm = getColorModel(image);
64. GraphicsEnvironment ge = GraphicsEnvironment 65. .getLocalGraphicsEnvironment();
66. GraphicsDevice gd = ge.getDefaultScreenDevice(); 67. GraphicsConfiguration gc = gd.getDefaultConfiguration(); 68. BufferedImage bi = gc.createCompatibleImage(w, h, cm.getTransparency());
69. Graphics2D g = bi.createGraphics();
70. g.drawImage(image, 0, 0, null);
71. g.dispose();
72. return bi;
73. }
74. public static BufferedImage readImage(InputStream is) { 75. BufferedImage image = null;
76. try {
77. image = ImageIO.read(is);
78. } catch (IOException e) {
79. // TODO Auto-generated catch block
80. e.printStackTrace();
81. }
82. return image;
83. }
84.
85. public static BufferedImage readImage(byte[] imageByte) { 86. ByteArrayInputStream bais = new ByteArrayInputStream(imageByte);
87. BufferedImage image = readImage(bais);
88. return image;
89. }
90. public static void encodeGIF(BufferedImage image, OutputStream out)
91. throws IOException {
92. Gif89Encoder encoder = new Gif89Encoder(image); 93. encoder.encode(out);
94. }
95. /**
96. *
97. * @param bi
98. * @param type
99. * @param out
100. */
101. public static void printImage(BufferedImage bi, String type,
102. OutputStream out) {
103. try {
104. if (type.equals(TYPE_GIF))
105. encodeGIF(bi, out);
106. else
107. ImageIO.write(bi, type, out);
108. } catch (IOException e) {
109. // TODO Auto-generated catch block 110. e.printStackTrace();
111. }
112. }
113. /**
114. * Get image type from byte[]
115. *
116. * @param textObj
117. * image byte[]
118. * @return String image type
119. */
120. public static String getImageType(byte[] textObj) { 121. String type = TYPE_NOT_AVAILABLE; 122. ByteArrayInputStream bais = null; 123. MemoryCacheImageInputStream mcis = null; 124. try {
125. bais = new ByteArrayInputStream(textObj); 126. mcis = new MemoryCacheImageInputStream(bais); 127. Iterator itr = ImageIO.getImageReaders(mcis); 128. while (itr.hasNext()) {
129. ImageReader reader = (ImageReader) itr.next(); 130. if (reader instanceof GIFImageReader) { 131. type = TYPE_GIF;
132. } else if (reader instanceof JPEGImageReader) {
133. type = TYPE_JPEG;
134. } else if (reader instanceof PNGImageReader) {
135. type = TYPE_PNG;
136. } else if (reader instanceof BMPImageReader) {
137. type = TYPE_BMP;
138. }
139. reader.dispose();
140. }
141. } finally {
142. if (bais != null) {
143. try {
144. bais.close();
145. } catch (IOException ioe) { 146. if (_log.isWarnEnabled()) { 147. _log.warn(ioe);
148. }
149. }
150. }
151. if (mcis != null) {
152. try {
153. mcis.close();
154. } catch (IOException ioe) { 155. if (_log.isWarnEnabled()) { 156. _log.warn(ioe);
157. }
158. }
159. }
160. }
161. if (_log.isDebugEnabled()) {
162. _log.debug("Detected type " + type); 163. }
164. return type;
165. }
166. private static Log _log = LogFactory.getLog(ImageUtil.class);
167. }
注意:对gif格式的图片进行处理的时候,需要另外一下jar包:gif89.jar,因为gif格式的图片不能使用ImageIO进行输出。
如需将图片存放到数据库中,只需要修改红色部分,将图片以blob格式保存到数据库中,显示时以byte[]格式读出,使用ImageUtil.printImage()进行输出。