一,介绍
common-fileupload是appache的开源组件,基于该组件可以轻松实现文件上传的功能,strust框架的文件上传功能也是基于该组件。
二,使用
1,导入两个jar包:common-fileupload.jar和common-io.jar,fileupload依赖于io包,两个jar包可到appache官网上下载.
2,示例性代码(基于官方示例代码改动):
// Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(); // Parse the request FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); // 普通表单域 if (item.isFormField()) { System.out.println("Form field " + name + " with value " + Streams.asString(stream) + " detected."); } else { // 文件域 System.out.println("File field " + name + " with file name " + item.getName() + " detected."); String filename = item.getName(); if (filename != null) { // 解决IE浏览器传递的是附件全路径的问题,Firefox传递的是文件名 filename = FilenameUtils.getName(filename); } // Process the input stream if (stream.available() != 0) // 上传的附件不为空,则存储到磁盘中 { Streams.copy(stream, new FileOutputStream( "I:/temp/" + filename), true); } } } }