文件上传<一>
原文:http://jcyanfan.iteye.com/blog/266542
进行文件上传一般有三种方式
1. 使用 fileUpLoad
2. 使用 smartFileUpLoad(fileUpLoad 优于smartfileupload)
3. 自己编写类似的程序进行解析
fileUpLoad 是 apache 的一个开源项目,用来进行解析带有文件的请求处理。著名的 struts 的FormFile 就是用的它进行解析处理的。
4、 依赖包:commons-io
1. 首先页面上我们需要将表单设置下面类似的参数:
< form method="post" enctype="multipart/form-data" action=”” >
2. 然后我们需要在工程里导入所需要的包,可以在 apache 网站上下载:
http://jakarta.apache.org/commons/fileupload/
3. 在我们的servlet中可以获取到request参数,然后可以这样取传递过来的字段参数及文件参数:
下载commons-fileupload.jar放到Project-name\WEB-INF\lib下
import javax.servlet.*;import javax.servlet.http.*;import java.io.*;import java.util.*;import java.util.regex.*;import org.apache.commons.fileupload.*;public class FileUpload extends HttpServlet { private static final String CONTENT_TYPE = "text/html; charset=GB2312"; //Process the HTTP Post request public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType(CONTENT_TYPE); PrintWriter out = response.getWriter(); try { //临时缓冲文件目录,此处系统默认 File tempfile = new File(System.getProperty("java.io.tmpdir")); DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); // 设置最多只允许在内存中存储的数据,单位:字节 diskFileItemFactory.setSizeThreshold(4096); //设置缓冲区目录,一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录 diskFileItemFactory.setRepository(tempfile); ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory); //DiskFileUpload upload = new DiskFileUpload(diskFileItemFactory); //设置编码,解决上传文件名乱码 upload.setHeaderEncoding("GBK"); // 设置允许用户上传文件大小,单位:字节,这里设为2M upload.setSizeMax(2 * 1024 * 1024); //开始读取上传信息 List fileItems = upload.parseRequest(request); // 依次处理每个上传的文件 Iterator iter = fileItems.iterator(); //正则匹配,过滤路径取文件名 String regExp = ".+(.+)$"; //过滤掉的文件类型 String[] errorType = { ".exe", ".com", ".cgi", ".asp"}; 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"); } } //保存上传的文件到指定的目录 //在下文中上传文件至数据库时,将对这里改写 item.write(new File("d:\" + m.group(1))); out.print(name + " " + size + ""); } } } } catch (IOException e) { e.printStackTrace(); } catch (FileUploadException e) { //e.printStackTrace(); } }}