J2EE中的文件上传插件使用方法

来源:互联网 发布:mysql数据库基础教程 编辑:程序博客网 时间:2024/06/06 01:48

首先在http://archive.apache.org/dist/这里下载所需的插件jar包

1. commons-fileupload-1.3.1.jar

2. commons-io.jar

然后添加html文件:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <title>index.html</title>    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="this is my page">    <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->  </head>  <body>   <form action="../servlet/FileUpload" method="post" enctype="multipart/form-data" name="form1">   <input type="hidden" name="id" value="<%=id %>">  <input type="file" name="file">  <input type="submit" name="Submit" value="upload"></form>  </body></html>

然后添加相应的servlet:

import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletConfig;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.commons.fileupload.*;import java.util.*;import java.util.regex.*;import java.io.*;import org.apache.commons.fileupload.servlet.*;import org.apache.commons.fileupload.disk.DiskFileItemFactory;public class FileUpload extends HttpServlet { @Overridepublic void init(ServletConfig config) throws ServletException {this.config = config;  //读配置文件}private ServletConfig config = null;private File tempPath = new File("D:\\upload\\temp\\"); // 用于存放临时文件的目录public void destroy() {config = null;super.destroy();}public void doPost(HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException {int id = -1;String uploadPath = config.getInitParameter("uploadPath"); // 用于存放上传文件的目录res.setContentType("text/html; charset=GB2312");PrintWriter out = res.getWriter();System.out.println(req.getContentLength());System.out.println(req.getContentType());DiskFileItemFactory factory = new DiskFileItemFactory();// maximum size that will be stored in memoryfactory.setSizeThreshold(4096);// the location for saving data that is larger than getSizeThreshold()factory.setRepository(tempPath);ServletFileUpload upload = new ServletFileUpload(factory);// maximum size before a FileUploadException will be thrownupload.setSizeMax(1000000);try {List fileItems = upload.parseRequest(req);// assume we know there are two files. The first file is a small// text file, the second is unknown and is written to a file on// the serverIterator iter = fileItems.iterator();// 正则匹配,过滤路径取文件名String regExp = ".+\\\\(.+)$";// 过滤掉的文件类型String[] errorType = { ".exe", ".com", ".cgi", ".jsp" };Pattern p = 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 = p.matcher(name);boolean result = m.find();if (result) {for (int temp = 0; temp < errorType.length; temp++) {if (m.group(1).endsWith(errorType[temp])) {throw new IOException(name + ": wrong type");}}try {// 保存上传的文件到指定的目录// 在下文中上传文件至数据库时,将对这里改写item.write(new File(uploadPath + ".jpg"));out.print(name + "  " + size + "<br>");} catch (Exception e) {out.println(e);}} else {throw new IOException("fail to upload");}}}} catch (IOException e) {out.println(e);} catch (FileUploadException e) {out.println(e);}}}


上面servlet中的init函数是用来读取配置文件用的,这里的config需要在web.xml文件中进行设置,web.xml配置如下:

<servlet><description>upload a file to server</description><display-name>FileUpload</display-name><servlet-name>FileUpload</servlet-name><servlet-class>com.bjsxt.shopping.util.servlet.FileUpload</servlet-class><init-param><param-name>uploadPath</param-name><param-value>D:\\java\\     <!--这里是需要上传到的文件路径--></param-value></init-param></servlet><servlet-mapping><servlet-name>FileUpload</servlet-name><url-pattern>/servlet/FileUpload</url-pattern></servlet-mapping>




0 0