FileItemFactory factory = newDiskFileItemFactory();//创建文件上传处理器
ServletFileUpload upload = newServletFileUpload(factory);//开始解析请求信息
List items = null;try{
items=upload.parseRequest(request);
}catch(FileUploadException e) {
e.printStackTrace();
}//对所有请求信息进行判断
Iterator iter =items.iterator();while(iter.hasNext()) {
FileItem item=(FileItem) iter.next();//信息为普通的格式
if(item.isFormField()) {
String fieldName=item.getFieldName();
String value=item.getString();
request.setAttribute(fieldName, value);
}//信息为文件格式
else{
String fileName=item.getName();
String suffix= fileName.substring(fileName.lastIndexOf('.'));//图片名
System.out.println("图片名字"+fileName);//后缀名
System.out.println(suffix);int index = fileName.lastIndexOf("\");
fileName= fileName.substring(index + 1);
request.setAttribute("realFileName", fileName);//图片url
String basePath = getServletConfig().getServletContext().getRealPath("/")+"img";
System.out.println(basePath);//新文件名
String newFileName = new Date().getTime() +suffix;
System.out.println(newFileName);
File file= newFile(basePath, newFileName);try{
item.write(file);int userId = (Integer) request.getSession().getAttribute("id");
System.out.println("userId:" +userId);//存图片信息
imagsTT.ImagsUp(userId, newFileName,basePath);
session.setAttribute("imgurl", "img/" +newFileName);
System.out.print("用图片返回查询的数据"+"img/" +newFileName);
}catch(Exception e) {
e.printStackTrace();
}
}
request.setAttribute("msg","文件上传成功!");
getServletContext().getRequestDispatcher("/My.jsp").forward(request, response);return;
}