DiskFileItemFactory对象的工厂,可以设定缓冲区大小和存放临时文件目录。
void | setRepository(java.io.File repository) 默认是System.getProperty("java.io.tmpdir"),即操作系统默认临时文件夹路径 Sets the directory used to temporarily store files that are larger than the configured size threshold. |
void | setSizeThreshold(int sizeThreshold) 以字节为单位,默认是10KSets the size threshold beyond which files are written directly to disk. |
ServletFileUpload This class handles multiple files per single HTML widget, sent using multipart/mixed
encoding type, as specified by RFC 1867. Use parseRequest(HttpServletRequest)
to acquire a list of FileItem
s associated with a given HTML widget.
处理表单数据,将数据封装到 FileItem 对象中。
FileItem 用来封装表单中的元素和数据。
void | delete() 手动删除临时文件Deletes the underlying storage for a file item, including deleting any associated temporary disk file. |
byte[] | get() 获取上传文件的二进制数组Returns the contents of the file item as an array of bytes. |
String | getContentType() 获取上传文件的文件类型Returns the content type passed by the browser or null if not defined. |
String | getFieldName() 获取组件的name属性Returns the name of the field in the multipart form corresponding to this file item. |
InputStream | getInputStream() 获取上传文件的输入流Returns an InputStream that can be used to retrieve the contents of the file. |
String | getName() 获取上传文件的文件名Returns the original filename in the client's filesystem, as provided by the browser (or other client software). |
long | getSize() 获取上传文件的大小,字节为单位Returns the size of the file item. |
String | getString() 获取组件的value属性Returns the contents of the file item as a String, using the default character encoding. |
String | getString(java.lang.String encoding) 以某种编码形式解码,获取组件的value属性Returns the contents of the file item as a String, using the specified encoding. |
boolean | isFormField() 判断当前item是否是普通文本组件Determines whether or not a FileItem instance represents a simple form field. |
boolean | isInMemory() 判断文件是否存储在内存中Provides a hint as to whether or not the file contents will be read from memory. |
void | write(java.io.File file) 将上传文件写出到服务器的硬盘上,参数指定文件A convenience method to write an uploaded item to disk. |
例子:
jsp页面中
<form action="servlet/UploadServlet" enctype="multipart/form-data" method="post">
<input type="text" name="userName" value="xxc">
<input type="file" name="file">
<input type="submit" value="上传">
</form>
在Servlet中
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
DiskFileItemFactory factory = new DiskFileItemFactory();//对象的工厂,可以设定缓冲区大小和存放临时文件目录。
factory.setSizeThreshold(600);//参数是以字节为单位的int值,如果从没有调用该方法设置此临界值,将会采用系统默认值10KB。
factory.setRepository(new File(this.getServletContext().getRealPath("/temp")));//当上传文件超过上面设置的值时,就将临时文件存储在硬盘上。
ServletFileUpload upload = new ServletFileUpload(factory);//处理表单数据,将数据封装到 FileItem 对象中。
//upload.setHeaderEncoding("UTF-8");
String[] allowTypes = new String[]{"jpg","xls"}; //将服务器端所能接受的上传文件类型,写在一个数组里。
List<FileItem> fileItems = null;//用来封装表单中的元素和数据。构造函数时,需要传入一个request。
try {
fileItems = upload.parseRequest(request);
Iterator<FileItem> iterator = fileItems.iterator();
while(iterator.hasNext()){
FileItem item = iterator.next();
if(item.isFormField()){
String field = item.getFieldName();//获取组件的name属性
String value = item.getString("UTF-8");//参数可写编码,防止文本组件的值乱码
//String name = item.getName();//这个应该是上传文件的文件名 当用于不是上传文件组件时候,一律返回null
}else{
/**
* 上传方式一 这个方法看了源码之后大概意思是,首先它会进行判断,如果数据存在于内存中的就会象方式二这么上传数据,因为前面做了验证,只有小于600K的数据才
* 存在于内存中,如果数据不存在于内存中就采用类似方式三的方法进行上传数据,只不过源码中将输入流copy到输出流用的是IOUtils.copy(fis, fos);
* org.apache.commons.io.IOUtils;
* */
String contentType = item.getContentType();//获取上传文件类型
List<String> allowTypesList = Arrays.asList(allowTypes);//将数组转换为集合
if(!allowTypesList.contains(contentType)){//用当前Item的文件类型和集合中的类型比较
System.out.println("不符合上传类型");
return;
}
String fileName = item.getName();//获取上传文件的文件名
String filePath = this.getServletContext().getRealPath("/Files");//获取当前项目根目录下的Files文件夹的在服务器硬盘上的真实路径
item.write(new File(filePath+"/"+fileName));
/**上传方式二 */
/*FileOutputStream fos = new FileOutputStream(filePath+"/"+fileName);
Streams.copy(item.getInputStream(), fos, false);//将输入流拷贝到输出流,输入流是客户端传过来的,输出流是服务器端写到硬盘上的
fos.close();*/
//item.delete();//手动删除临时文件
/**上传方式三 这种方式不推荐,因为文件过大就会导致内存溢出异常*/
/*FileOutputStream fos = new FileOutputStream(filePath+"/"+fileName);
byte[] buf = item.get();
fos.write(buf);*/
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}