- 浏览: 246615 次
- 性别:
- 来自: 湖南
文章分类
- 全部博客 (194)
- java (23)
- 数据结构和算法 (5)
- oracle (7)
- sql server (1)
- mysql (5)
- Ajax (5)
- JSTL (7)
- jsp (20)
- 组件 (11)
- C++可视化 (0)
- javascript (14)
- c/c++ (0)
- XML (6)
- 只是扩宽 (0)
- 设计模式 (3)
- 正则表达式 (3)
- 心情和感悟 (4)
- ACM (3)
- HTML/css (9)
- 软件破解 (2)
- spring (1)
- struts (15)
- hibernate (10)
- Servlet (2)
- sql (2)
- 面试题 (1)
- struts2 (22)
- Unix/Linux (0)
- javamail (1)
- svn (1)
- 异常 (3)
- EJB (3)
- jquery (2)
- android (1)
最新评论
-
lianlupengUestc:
From my testing (Struts2 versio ...
struts2 注解 -
yulongxiang:
非常感谢!!!!!!!
使用动态ActionForm(转)
Apache commons-fileupload是一个很好的文件上传工具,最近使用commons-fileupload实现了图片的上传及显示,可将图片保存在 指定的文件夹中,也可以将图片存放在数据库,并支持四种常用的图片格式:jpg,png,gif,bmp。 首先,跟上传一般文件一样,需要写一个servlet来处理上传的文件,你可以修改保存路径或选择将图片保存在数据库中,只需要做简单的修改就行了,servlet代码如下:
FileUploadServlet.java
servlet中使用到一个ImageUtil类,其中封装了图片处理的实用方法,用于读写图片,代码如下:
ImageUtil.java
注意:对gif格式的图片进行处理的时候,需要另外一下jar包:gif89.jar,因为gif格式的图片不能使用ImageIO进行输出。 如需将图片存放到数据库中,只需要修改红色部
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 javax.servlet.ServletException; 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 com.ek.image.ImageUtil;public class FileUploadServlet extends HttpServlet {/** * */ private static final long serialVersionUID = 1L;private static String filePath = "";/** * Destruction of the servlet. <br> */public void destroy() { 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)); ServletFileUpload upload = new ServletFileUpload(factory); // 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 = ".+\\\\(.+\\.?())$"; Pattern fileNamePattern = Pattern.compile(regExp); 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); InputStream stream = item.getInputStream(); 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); if (type.equals(ImageUtil.TYPE_NOT_AVAILABLE)) throw new Exception("file is not a image"); BufferedImage myImage = ImageUtil .readImage(imageByte); // display the image 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(); } catch (Exception e) { e.printStackTrace(); } } else { 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("/"); }}
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 javax.imageio.ImageIO; 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 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;/** * @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_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(); }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(); }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; }public static BufferedImage readImage(InputStream 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; }public static void encodeGIF(BufferedImage image, OutputStream out) 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(); } }/** * 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; try { bais = new ByteArrayInputStream(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; } 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); } } } if (mcis != null) { try { mcis.close(); } catch (IOException ioe) { if (_log.isWarnEnabled()) { _log.warn(ioe); } } } } if (_log.isDebugEnabled()) { _log.debug("Detected type " + type); } return type; }private static Log _log = LogFactory.getLog(ImageUtil.class); }
注意:对gif格式的图片进行处理的时候,需要另外一下jar包:gif89.jar,因为gif格式的图片不能使用ImageIO进行输出。 如需将图片存放到数据库中,只需要修改红色部
发表评论
-
log4j --文件输出路径
2010-10-27 23:23 1399利用占位符,然后再利用servlet给占位符赋值 log ... -
log4j
2010-10-24 23:27 864log4j.rootLogger=[level], appen ... -
上传文件
2010-10-11 14:41 1510上传: 需要导入两个包:commons-fileupload- ... -
有关FileUpload组件的使用和调试的经验(转)
2010-08-30 12:29 778在通过使用FileUpload组件上传的过程中,通过自己的调试 ... -
jfreechart设置饼图百分比
2010-08-30 12:28 1446PiePlot3D plot=(PiePlot3D)c ... -
javamail发送邮件的简单实例 (转
2010-08-30 12:27 782第一个类:MailSenderInfo.java packa ... -
jfreechart中文乱码问题解决方案
2010-08-30 12:25 727jfreechart中文乱码问题解 ... -
使用 JFreeChart来创建基于web的图表 (转)
2010-08-30 12:25 726使用 JFreeChart来创建基于web的图表 ... -
jfreechart使用总结(转)
2010-08-30 12:22 967这里分三部分来介绍 jFreeChart 。第一部分介绍jFr ... -
Enctype=multipart/form-data 有什么用?
2010-08-30 12:21 1258ENCTYPE="multipart/form-da ...
相关推荐
上传图片时,选择图片之后显示在页面上,现成的代码,直接使用即可
jsp 图片上传立即显示
简单的servlet+jsp图片上传并显示图片,解压就能用,感觉好就给个好评!
使用支持中文的jspSmartUpload组件,自己制作了一个具有上传图片功能的简易新闻发布页面,带列表页,仅作为上传图片的参考。
使用jsp+tag编程,实现上传并显示图片功能。
内容索引:JSP源码,上传下载,图片上传,进度条 JSP图片上传实例,在上传图片的时候可以加图片描述,显示图片上传进度,上传类库cos.jar。
JSP上传图片并裁切及放大显示,常用的JSP程序,看到有不少的图片上传、缩放及裁切程序,手痒就写了个,网上见的多的都是ASP/ASP.NET、php的,还没有发现有JSP的,写时候参数程序比较少,因此程序并不完善,只是实现...
JSP实训六student(JSP实现图片上传和读取显示).doc
jsp文件上传 工具MyEclipse 6.0
简单的jsp图片上传实例,包括上传到本地文件夹及显示
关于在jsp页面上传图片的代码, Apache commons-fileupload是一个很好的文件上传工具,最近使用commons-fileupload实现了图片的上传及显示,可将图片保存在指定的文件夹中,也可以将图片存放在数据库,并支持四种常用...
jspsmartupload实现上传图片显示缩略图,放在tomcat工程目录下访问即可,绝对好用!
从电脑里选择图片,图片的格式可以加以限制,选择图片后可实时显示预览
使用jsp做的简易相册,实现了上传图片,查看相册中所有图片,查看相册中所有图片时图片分页显示,点击图片可查看原图,可上下翻看图片。内含有smartupload.jar包。如果配好smartupload.jar包后可以将该文件夹直接...
SWFUpload+struts+jsp版的图片上传和显示
第一次上传的代码有错,现在这个版本的,附带了正确的代码以及附带了jspSmartUpload.jar,直接解压缩后部署在Tomcat的webapps下即可。
jsp上传图片并生成缩略图example upload pictures and zoom it
struts1上传图片,保存数据库,再显示jsp页面
1. 基于标准HTTP协议,支持ASP,ASP.NET(C#),ASP.NET(VB),JSP,PHP等服务端语言。 2. 支持BMP,JPG,GIF,...12. 显示上传进度。 13. 自定义图片水印。 14. 免费提供JavaScript SDK包,方便您将插件快速集成到已有网站中。
jsp上传图片源码。写项目实在是需要耐心呀