文件上传涉及到的两个Jar包:
- com.springsource.org.apache.commons.fileupload
- com.springsource.org.apache.commons.io
Html部分
<!-- form表单提交方式必须为post -->
<!-- form必须要设置enctype="multipart/form-data"属性,否则后台无法解析 -->
<form action="/uploading/Uploading" method="post" enctype="multipart/form-data">
用户:<input type="text" name="username"/><br>
上传:<input type="file" name="file"/><br>
<input type="submit" value="提交">
</form>
Servlet后台处理
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
//工厂
DiskFileItemFactory dfif = new DiskFileItemFactory();
//解析
ServletFileUpload sfu = new ServletFileUpload(dfif);
//解析
try {
List<FileItem> fItem = sfu.parseRequest(request);
FileItem file = fItem.get(1);
//获取WEB-INF绝对路径
String path = this.getServletContext().getRealPath("/WEB-INF/files");
System.out.println(path);
//获取文件名
String fileName = file.getName();
//检索文件名是否为绝对路径
int isExist = fileName.lastIndexOf("\\");
if(isExist!=-1){
fileName = fileName.substring(isExist+1);
}
//解决文件重名问题
fileName = UUID.randomUUID().toString()+ "_" + fileName ;
//获取16进制文件名
String hashString = Integer.toHexString(fileName.hashCode());
//创建目录
File fil = new File(path+"\\"+hashString.charAt(0)+"\\"+hashString.charAt(1));
fil.mkdirs();
//创建文件
File saveFile = new File(fil,fileName);
//写入文件
file.write(saveFile);
} catch (FileUploadException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
} catch (Exception e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}