protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//判断是否是多段数据(只有是多段数据才是文件上传)
//多段数据返回true,否则返回false
if(ServletFileUpload.isMultipartContent(req)){
//创建FileItemFactory工厂实现类
FileItemFactory factory = new DiskFileItemFactory();
//创建用于解析数据的工具类ServletFileUpload类
ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
try {
//解析上传的数据,得到每一个表单项FileItem
List<FileItem> list = servletFileUpload.parseRequest(req);
//判断每个表单项是普通类型还是上传的文件
for(FileItem item : list){
if(item.isFormField()){
//普通表单项
System.out.println("表单项的name:"+item.getFieldName());
//使用UTF-8解析,防止乱码
System.out.println("表单项的value:"+item.getString("UTF-8"));
}else {
//上传的文件
System.out.println("表单项的name:"+item.getFieldName());
System.out.println("上传的文件名为:"+item.getName());
//将此文件写到d盘根目录
item.write(new File("C:\\Users\\songsong.chen\\Desktop\\web-hands-on-exercise\\web-hands-on-exercise-web\\src\\main\\webapp\\WebRoot"+item.getName()));
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}