jsp文上传如何实现将上传的多个文件都同时显示出来
1个回答
展开全部
需要写一个servlet来处理上传的文件,你可以修改保存路径或选择将图片保存在数据库中,只需要做简单的修改就行了,servlet代码如下:
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;
publicclass FileUploadServlet extends HttpServlet {
/**
*
*/
privatestaticfinallong serialVersionUID = 1L;
privatestatic String filePath = "";
/**
* Destruction of the servlet.
*/
publicvoid destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doPost method of the servlet.
*
* 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
*/
publicvoid 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 = newbyte[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))
thrownew 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.
*
* @throws ServletException
* if an error occure
*/
public void init() throws ServletException {
// Change the file path here
filePath = getServletContext().getRealPath("/");
}
}
servlet中使用到一个ImageUtil类,其中封装了图片处理的实用方法,用于读写图片,代码如下:
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
*/
publicclass ImageUtil {
publicstaticfinal String TYPE_GIF = "gif";
publicstaticfinal String TYPE_JPEG = "jpeg";
publicstaticfinal String TYPE_PNG = "png";
publicstaticfinal String TYPE_BMP = "bmp";
publicstaticfinal String TYPE_NOT_AVAILABLE = "na";
privatestatic ColorModel getColorModel(Image image)
throws InterruptedException, IllegalArgumentException {
PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false);
if (!pg.grabPixels())
thrownew IllegalArgumentException();
return pg.getColorModel();
}
privatestaticvoid loadImage(Image image) throws InterruptedException,
IllegalArgumentException {
Component dummy = new Component() {
privatestaticfinallong serialVersionUID = 1L;
};
MediaTracker tracker = new MediaTracker(dummy);
tracker.addImage(image, 0);
tracker.waitForID(0);
if (tracker.isErrorID(0))
thrownew IllegalArgumentException();
}
publicstatic 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;
}
publicstatic BufferedImage readImage(InputStream is) {
BufferedImage image = null;
try {
image = ImageIO.read(is);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return image;
}
publicstatic BufferedImage readImage(byte[] imageByte) {
ByteArrayInputStream bais = new ByteArrayInputStream(imageByte);
BufferedImage image = readImage(bais);
return image;
}
publicstaticvoid encodeGIF(BufferedImage image, OutputStream out)
throws IOException {
Gif89Encoder encoder = new Gif89Encoder(image);
encoder.encode(out);
}
/**
*
* @param bi
* @param type
* @param out
*/
publicstaticvoid 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
*/
publicstatic 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;
} elseif (reader instanceof JPEGImageReader) {
type = TYPE_JPEG;
} elseif (reader instanceof PNGImageReader) {
type = TYPE_PNG;
} elseif (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;
}
privatestatic Log _log = LogFactory.getLog(ImageUtil.class);
}
注意:对gif格式的图片进行处理的时候,需要另外一下jar包:gif89.jar,因为gif格式的图片不能使用ImageIO进行输出。
如需将图片存放到数据库中,只需要修改红色部分,将图片以blob格式保存到数据库中,显示时以byte[]格式读出,使用ImageUtil.printImage()进行输出。
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;
publicclass FileUploadServlet extends HttpServlet {
/**
*
*/
privatestaticfinallong serialVersionUID = 1L;
privatestatic String filePath = "";
/**
* Destruction of the servlet.
*/
publicvoid destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doPost method of the servlet.
*
* 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
*/
publicvoid 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 = newbyte[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))
thrownew 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.
*
* @throws ServletException
* if an error occure
*/
public void init() throws ServletException {
// Change the file path here
filePath = getServletContext().getRealPath("/");
}
}
servlet中使用到一个ImageUtil类,其中封装了图片处理的实用方法,用于读写图片,代码如下:
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
*/
publicclass ImageUtil {
publicstaticfinal String TYPE_GIF = "gif";
publicstaticfinal String TYPE_JPEG = "jpeg";
publicstaticfinal String TYPE_PNG = "png";
publicstaticfinal String TYPE_BMP = "bmp";
publicstaticfinal String TYPE_NOT_AVAILABLE = "na";
privatestatic ColorModel getColorModel(Image image)
throws InterruptedException, IllegalArgumentException {
PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false);
if (!pg.grabPixels())
thrownew IllegalArgumentException();
return pg.getColorModel();
}
privatestaticvoid loadImage(Image image) throws InterruptedException,
IllegalArgumentException {
Component dummy = new Component() {
privatestaticfinallong serialVersionUID = 1L;
};
MediaTracker tracker = new MediaTracker(dummy);
tracker.addImage(image, 0);
tracker.waitForID(0);
if (tracker.isErrorID(0))
thrownew IllegalArgumentException();
}
publicstatic 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;
}
publicstatic BufferedImage readImage(InputStream is) {
BufferedImage image = null;
try {
image = ImageIO.read(is);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return image;
}
publicstatic BufferedImage readImage(byte[] imageByte) {
ByteArrayInputStream bais = new ByteArrayInputStream(imageByte);
BufferedImage image = readImage(bais);
return image;
}
publicstaticvoid encodeGIF(BufferedImage image, OutputStream out)
throws IOException {
Gif89Encoder encoder = new Gif89Encoder(image);
encoder.encode(out);
}
/**
*
* @param bi
* @param type
* @param out
*/
publicstaticvoid 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
*/
publicstatic 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;
} elseif (reader instanceof JPEGImageReader) {
type = TYPE_JPEG;
} elseif (reader instanceof PNGImageReader) {
type = TYPE_PNG;
} elseif (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;
}
privatestatic Log _log = LogFactory.getLog(ImageUtil.class);
}
注意:对gif格式的图片进行处理的时候,需要另外一下jar包:gif89.jar,因为gif格式的图片不能使用ImageIO进行输出。
如需将图片存放到数据库中,只需要修改红色部分,将图片以blob格式保存到数据库中,显示时以byte[]格式读出,使用ImageUtil.printImage()进行输出。
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询