//需要在<form>中加入如下属性<form>中
//enctype="multipart/form-data"
//在jsp中加入<input type="file">标签
//一下是servlet中的代码
//1、判断form表单是否有文件上传
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
//提前定义需要获取的数据
String comments = "";
String usertype = "";
String imges = "";
if(isMultipart){//如果表单有上传文件
//创建一个工厂类对象
DiskFileItemFactory fileitem = new DiskFileItemFactory();
//获取上传的对象
ServletFileUpload upload = new ServletFileUpload(fileitem);
//设置获取文件的格式
upload.setHeaderEncoding("utf-8");
//设置上传文件的大小
upload.setSizeMax(1024*1024*2);
try {
//将获取的数据建立一个集合
List<FileItem> filelist = upload.parseRequest(request);
//获取集合的迭代器
Iterator<FileItem> it = filelist.iterator();
//遍历
while (it.hasNext()) {
//将集合中的元素赋值给item
FileItem item = (FileItem) it.next();
if(item.isFormField()){//判断是否是普通元素
//是普通元素将name和value设置格式
String name = new String(item.getFieldName().getBytes("iso8859-1"),"utf-8");
String value = newString(item.getString().getBytes("iso8859-1"),"utf-8");
//如果普通元素的name属性姓名与comments相同将value值赋值给comments
if("comments".equals(name)){
comments = value;
}elseif("usertype".equals(name)){
usertype = value;
}
}else{
//如果不是普通数据是文件
//获取文件的名字
Stringfilename = item.getName();
//建立新的文件名
String newfilename = new Date().getTime()+filename.substring(filename.indexOf("."));
//将文件储存在逗号前面的文件夹内,重命名为逗号后面的字符串
File file = new File(getServletContext().getRealPath ("/images/photo"),newfilename);
//将新的名字赋值给数据库中的列名
imges= newfilename;
//开始写入数据到服务器
try {
item.write(file);
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}//else的括号
}//while循环的括号
}catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}//最开始if的括号
//后面就是获取数据并调用service中的方法进行数据库的更改并跳转页面
//一下是jsp页面的代码,在显示的位置更改文件路径
src="http://localhost:8899/my12306/images/<%=user.getImges()%>"