ITeye博客

使用apache.commons.fileupload组件来进行文件上传

zhou_wu · 2011-01-27 11:00 · j2ee · 编程语言 · Markdown

  1. 从www.apache.org的common项目下搞到commons-fileupload.jar 和commons-io.jar,导入项目。

  2. jsp页面中,form的属性设置要求为:

  1. 创建处理请求的Servlet:

<span style="font-size: medium;">DiskFileItemFactory factory = new DiskFileItemFactory();
		// 获得项目根路径
		String path = request.getRealPath("/");	
		// 设置缓存路径
		factory.setRepository(new File(path));
		// 设置文件缓存到硬盘的大小临界值
		factory.setSizeThreshold(1024 * 1024);

		ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
		try {
			// 指定解析request
			List<FileItem> list = (List<FileItem>)
					servletFileUpload.parseRequest(request);
			for (FileItem item : list)
			{
				// 非文件的表单字段
				if (item.isFormField() == true){
					String filedName = item.getFieldName(); // 获得字段名
					String value = item.getString("UTF-8"); // 获得字段值
					System.out.println("fieldName=" + filedName);
					System.out.println("value=" + value);
					
				}else{ //文件表单字段
					String fieldName = item.getFieldName(); // 获得字段名
					String value = item.getName();			// 获得文件名
					System.out.println("fieldName=" + fieldName);
					System.out.println("file path=" + value);
					// 处理浏览器兼容问题处理
					int index = value.lastIndexOf("\\");
					String fileName = value.substring(index + 1);
					
					item.write(new File(path, fileName));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}</span>

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。