//创建一个下载的方法,需要时调用
private void upload(HttpServletRequest request, HttpServletResponse response) {
//1.创建一个磁盘工厂对象
DiskFileItemFactory factory = new DiskFileItemFactory();
//2.通过工厂对象创建上传对象
ServletFileUpload fUpload = new ServletFileUpload(factory);
//3.通过上传对象解析前端发送的复合型表单数据
List list = null;
HashMap map = new HashMap<>();
Student student = new Student();
try {
//通过上传对象解析请求中的数据,获得集合
list = fUpload.parseRequest(request);
for (FileItem fItem:list) {
//判断是否非文本信息
if(!fItem.isFormField()){
//2.修改上传图片的名字
//使用UUID--生成唯一的ID值---wehfiw123%@#$!6fwef_f.jpg
UUID uuid = UUID.randomUUID();
System.out.println(uuid.toString());
String path = getServletContext().getRealPath("Upload");
File file = new File(path);
if(!file.exists()){
file.mkdirs();
}
//拼接路径和图片名字(uuid生成的随机字符串拼接上图片名字)
File file1 = new File(file, uuid.toString() + "_" + fItem.getName());
IOUtils.copy(fItem.getInputStream(),new FileOutputStream(file1));
//存储的路径不能为绝对路径
student.setImgUrl("Upload/"+uuid.toString() + "_" + fItem.getName());
}else{
//通过key(getFieldNmae--表单的name属性值)获取value(getString--表单的value值)
String value = map.get(fItem.getFieldName());
//第一次存储
if(value == null){
map.put(fItem.getFieldName(),fItem.getString());
}else{//多次存储(多选框)
map.put(fItem.getFieldName(),value+","+fItem.getString());
}
}
}
//利用该方法把map集合的数据存放到student对象中
BeanUtils.populate(student,map);
request.setAttribute("stu",student);
request.getRequestDispatcher("show.jsp").forward(request,response);
} catch (FileUploadException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (ServletException e) {
e.printStackTrace();
}
}