首先,页面中即JSP中需要如下的组件:
上传照片:
enctype="multipart/form-data">
而后在servlet中可以通过如下代码来完成文件的上传操作:
if(path.equals("/pic")){
//获得登录用户的id,用于创建新的文件夹,存放该用户上传的文件s
HttpSession session = request.getSession();
User user=(User)session.getAttribute("user");
long id=user.getId();
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload sfu = new ServletFileUpload(factory);
try {
List items = sfu.parseRequest(request);
for(int i =0;i
FileItem item =items.get(i);
if(item.isFormField()){
String name = item.getString();
System.out.println("name"+name);
}
else{
ServletContext context = getServletContext();
path =context.getRealPath("upload");
File file = new File(path+"pic_"+id);
file.mkdir();
String fileName1 = item.getName();
String fileName = fileName1.substring(fileName1.lastIndexOf("")+1);
file = new File(path+""+"pic_"+id+""+fileName);
item.write(file);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
|