Apache commons-fileupload是一个很好的文件上传工具,最近使用commons-fileupload实现了图片的上传及显示,可将图片保存在指定的文件夹中,也可以将图片存放在数据库,并支持四种常用的图片格式:jpg,png,gif,bmp。
首先,跟上传一般文件一样,需要写一个servlet来处理上传的文件,你可以修改保存路径或选择将图片保存在数据库中,只需要做简单的修改就行了,servlet代码如下:
FileUploadServlet.java
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.
- */
- public void 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
- */
- public void doPost(HttpServletRequest req, HttpServletResponse res)
- throws ServletException, IOException {
- res.setContentType("text/html; charset=UTF-8");
- DiskFileItemFactory factory = new DiskFileItemFactory();
- // maxi