依赖
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>${commons-fileupload.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
jsp的form表单
文件要以二进制的形式传输 enctype="multipart/form-data"
<form name="addNewCategoryForm" action="addNewCategory" method="post" enctype="multipart/form-data" onsubmit="return check(this)">
...
</form>
提交的二进制数据处理
DiskFileItemFactory itemFactory = new DiskFileItemFactory();
ServletFileUpload fileUpload = new ServletFileUpload(itemFactory);
//设置缓冲区的大小:
itemFactory.setSizeThreshold(1024 * 1024);
List items = null;
try {
//获得表单项集合
items = fileUpload.parseRequest(request);
for (Object item : items) {
FileItem fileItem = (FileItem)item;
//如果不是普通表单,即是文件类型
if(!fileItem.isFormField()) {
//获取文件存储目录
String fileFolder = request.getSession().getServletContext().getRealPath("img/category");
//获取文件名称
String fileName = fileItem.getName();
//获取文件后缀名
String suffix = fileName.substring(fileName.lastIndexOf("."));
//构建文件名
String newFileName = new Date().getTime() + suffix;
File file = new File(fileFolder,newFileName);
try {
if(!file.exists()) {
file.createNewFile();
}
//将表单内容写入该文件
fileItem.write(file);
} catch (Exception e) {
e.printStackTrace();
}
//删除临时文件
fileItem.delete();
}
//普通表单
if(fileItem.isFormField()) {
//获取name的值
System.out.println(fileItem.getFieldName());
try {
//获取value的值
String value = fileItem.getString("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}