本文实例为大家分享了jsp+servlet实现文件上传到服务器功能的具体代码,供大家参考,具体内容如下
项目目录结构大致如下:

正如我在上图红线画的三个东西:dao、service、servlet 这三层是主要的结构,类似 mvc 架构,dao是模型实体类(逻辑层),service是服务层,servlet是视图层,三者协作共同完成项目。
这里的user是由user表来定义的一个类,再封装增删改查等操作,实现从数据库查询与插入,修改与删除等操作,并实现了分页操作,也实现了将图片放到服务器上运行的效果。
dao层:主要实现了user类的定义,接口iuserdao的定义与实现(userdaoimpl);
service层:直接定义一个接口类iuserservice,与iuserdao相似,再实现其接口类userserviceimpl,直接实例化userdaoimpl再调用其方法来实现自己的方法,重用了代码。详见代码吧;
servlet层:起初是将表user 的每个操作方法都定义成一个servlet 去实现,虽然简单,但是太多了,不好管理,于是利用 基类baseservlet 实现了“反射机制”,通过获取的 action 参数自己智能地调用对应的方法,而userservlet则具体实现自己的方法,以供调用,方便许多,详见之前的博文或下述代码。
将文件上传到 tomcat 服务器的编译后运行的过程的某个文件关键要在每次编译后手动为其创建该文件夹来存放相应的上传文件,否则会导致每次重启 tomcat 服务器后该编译后的工程覆盖了原先的,导致上传文件存放的文件夹不存在,导致代码找不到该文件夹而报错,即上传不成功。如下图所示:

主要是考虑图片路径的问题,手工设置路径肯定不能保证不重复,所以取到上传图片的后缀名后利用随机生成的随机数作为图片名,这样就不会重复名字了:
string extendedname = picturepath.substring(picturepath.lastindexof("."),// 截取从最后一个'.'到字符串结束的子串。
picturepath.length());
// 把文件名称重命名为全球唯一的文件名
string uniquename = uuid.randomuuid().tostring();
savefilename = uniquename + extendedname;// 拼接路径名
增加用户时代码如下:
// 增
public void add(httpservletrequest request, httpservletresponse response)
throws servletexception, ioexception {
system.out.println("add方法被调用");
// 获取数据
int id = 0;
string username = null;
string password = null;
string sex = null;
date birthday = null;
string address = null;
string savefilename = null;
string picturepath = null;
// 得到表单是否以enctype="multipart/form-data"方式提交
boolean ismulti = servletfileupload.ismultipartcontent(request);
if (ismulti) {
// 通过fileitemfactory得到文件上传的对象
fileitemfactory fif = new diskfileitemfactory();
servletfileupload upload = new servletfileupload(fif);
try {
list<fileitem> items = upload.parserequest(request);
for (fileitem item : items) {
// 判断是否是普通表单控件,或者是文件上传表单控件
boolean isform = item.isformfield();
if (isform) {// 是普通表单控件
string name = item.getfieldname();
if ("id".equals(name)) {
id = integer.parseint(item.getstring("utf-8"));
system.out.println(id);
}
if ("sex".equals(name)) {
sex = item.getstring("utf-8");
system.out.println(sex);
}
if ("username".equals(name)) {
username = item.getstring("utf-8");
system.out.println(username);
}
if ("password".equals(name)) {
password = item.getstring("utf-8");
system.out.println(password);
}
if ("birthday".equals(name)) {
string birthdaystr = item.getstring("utf-8");
simpledateformat sdf = new simpledateformat(
"yyyy-mm-dd");
try {
birthday = sdf.parse(birthdaystr);
} catch (parseexception e) {
e.printstacktrace();
}
system.out.println(birthday);
}
if ("address".equals(name)) {
address = item.getstring("utf-8");
system.out.println(address);
}
if ("picturepath".equals(name)) {
picturepath = item.getstring("utf-8");
system.out.println(picturepath);
}
} else {// 是文件上传表单控件
// 得到文件名 xxx.jpg
string sourcefilename = item.getname();
// 得到文件名的扩展名:.jpg
string extendedname = sourcefilename.substring(
sourcefilename.lastindexof("."),
sourcefilename.length());
// 把文件名称重命名为全球唯一的文件名
string uniquename = uuid.randomuuid().tostring();
savefilename = uniquename + extendedname;
// 得到上传到服务器上的文件路径
// c:\\apache-tomcat-7.0.47\\webapps\\taobaoservlet4\\upload\\xx.jpg
string uploadfilepath = request.getsession()
.getservletcontext().getrealpath("upload/");
file savefile = new file(uploadfilepath, savefilename);
// 把保存的文件写出到服务器硬盘上
try {
item.write(savefile);
} catch (exception e) {
e.printstacktrace();
}
}
}
} catch (numberformatexception e) {
// todo auto-generated catch block
e.printstacktrace();
} catch (fileuploadexception e) {
// todo auto-generated catch block
e.printstacktrace();
}
}
// 2、封装数据
user user = new user(id, username, password, sex, birthday, address,
savefilename);
// 3、调用逻辑层api
iuserservice iuserservice = new userserviceimpl();
// 4、控制跳转
httpsession session = request.getsession();
if (iuserservice.save(user) > 0) {
system.out.println("添加新用户成功!");
list<user> users = new arraylist<user>();
users = iuserservice.listall();
session.setattribute("users", users);
response.sendredirect("userservlet?action=getpage");
} else {
system.out.println("添加新用户失败!");
printwriter out = response.getwriter();
out.print("<script type='text/javascript'>");
out.print("alert('添加新用户失败!请重试!');");
out.print("</script>");
}
}
修改用户时注意考虑图片更改和没更改这两种情况,图片更改时要先获取原图片并删除其在服务器上的图片,再添加新图片到服务器;图片不更改时则无需更新图片路径。
// 改
public void update(httpservletrequest request, httpservletresponse response)
throws servletexception, ioexception {
system.out.println("update方法被调用");
httpsession session = request.getsession();
// 获取数据
int id = (int)session.getattribute("id");
string username = null;
string password = null;
string sex = null;
date birthday = null;
string address = null;
string savefilename = null;
string picturepath = null;
iuserservice iuserservice = new userserviceimpl();
// 得到表单是否以enctype="multipart/form-data"方式提交
boolean ismulti = servletfileupload.ismultipartcontent(request);
if (ismulti) {
// 通过fileitemfactory得到文件上传的对象
fileitemfactory fif = new diskfileitemfactory();
servletfileupload upload = new servletfileupload(fif);
try {
list<fileitem> items = upload.parserequest(request);
for (fileitem item : items) {
// 判断是否是普通表单控件,或者是文件上传表单控件
boolean isform = item.isformfield();
if (isform) {// 是普通表单控件
string name = item.getfieldname();
if ("sex".equals(name)) {
sex = item.getstring("utf-8");
system.out.println(sex);
}
if ("username".equals(name)) {
username = item.getstring("utf-8");
system.out.println(username);
}
if ("password".equals(name)) {
password = item.getstring("utf-8");
system.out.println(password);
}
if ("birthday".equals(name)) {
string birthdaystr = item.getstring("utf-8");
simpledateformat sdf = new simpledateformat(
"yyyy-mm-dd");
try {
birthday = sdf.parse(birthdaystr);
} catch (parseexception e) {
e.printstacktrace();
}
system.out.println(birthday);
}
if ("address".equals(name)) {
address = item.getstring("utf-8");
system.out.println(address);
}
if ("picturepath".equals(name)) {
picturepath = item.getstring("utf-8");
system.out.println(picturepath);
}
} else {// 是文件上传表单控件
// 得到文件名 xxx.jpg
picturepath = item.getname();
if (picturepath != "") {// 有选择要上传的图片
// 得到文件名的扩展名:.jpg
string extendedname = picturepath.substring(
picturepath.lastindexof("."),// 截取从最后一个'.'到字符串结束的子串。
picturepath.length());
// 把文件名称重命名为全球唯一的文件名
string uniquename = uuid.randomuuid().tostring();
savefilename = uniquename + extendedname;// 拼接路径名
// 得到上传到服务器上的文件路径
// c:\\apache-tomcat-7.0.47\\webapps\\commonhelloworldservlet\\upload\\xx.jpg
string uploadfilepath = request.getsession()
.getservletcontext().getrealpath("upload/");
file savefile = new file(uploadfilepath,
savefilename);
// 把保存的文件写出到服务器硬盘上
try {
item.write(savefile);
} catch (exception e) {
e.printstacktrace();
}
// 3、调用逻辑层 api
// 根据id查询用户并获取其之前的图片
user user = iuserservice.getuserbyid(id);
string oldpic = user.getpicturepath();
string oldpicpath = uploadfilepath + "\\" + oldpic;
file oldpictodelete = new file(oldpicpath);
oldpictodelete.delete();// 删除旧图片
}
}
}
} catch (numberformatexception e) {
e.printstacktrace();
} catch (fileuploadexception e) {
e.printstacktrace();
}
}
system.out.println(id + "\t" + username + "\t" + password + "\t" + sex
+ "\t" + address + "\t" + picturepath + "\t" + birthday);
// 2、封装数据
user user = new user(id, username, password, sex, birthday, address,
savefilename);
if (iuserservice.update(user) > 0) {
system.out.println("修改数据成功!");
list<user> users = new arraylist<user>();
users = iuserservice.listall();
session.setattribute("users", users);
// 4、控制跳转
response.sendredirect("userservlet?action=getpage");
} else {
system.out.println("修改数据失败!");
printwriter out = response.getwriter();
out.print("<script type='text/javascript'>");
out.print("alert('修改数据失败!请重试!');");
out.print("</script>");
}
}
删除的话就比较简单了,直接获取原图片路径并删除,则原图片在服务器上被删除。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持硕编程。
- jsp+servlet实现文件上传与下载功能
- EJB3.0部署消息驱动Bean抛javax.naming.NameNotFoundException异常
- 在JSP中使用formatNumber控制要显示的小数位数方法
- 秒杀系统Web层设计的实现方法
- 将properties文件的配置设置为整个Web应用的全局变量实现方法
- JSP使用过滤器防止Xss漏洞
- 在JSP页面中动态生成图片验证码的方法实例
- 详解JSP 内置对象request常见用法
- 使用IDEA编写jsp时EL表达式不起作用的问题及解决方法
- jsp实现局部刷新页面、异步加载页面的方法
- Jsp中request的3个基础实践
- JavaServlet的文件上传和下载实现方法
- JSP页面的静态包含和动态包含使用方法


