Apache提供的commons-fileupload jar包实现文件上传确实很简单,最近要用Servlet/JSP做一个图片上传功能,在网上找了很多资料,大多是基于struts框架介绍的,还有些虽然也介绍common-fileupload的上传,但是那些例子比较老,有些类现在都废弃了。通过研究学习总结,终于完成了这个上传功能,下面与大家分享一下。
文件上传概述
实现web开发中的文件上传功能,需完成如下二步操作:
•在web页面中添加上传输入项
•在servlet中读取上传文件的数据,并保存到服务器硬盘中。
如何在web页面中添加上传输入项?
•标签用于在web页面中添加文件上传输入项,设置文件上传输入项时须注意:
•1、必须要设置input输入项的name属性,否则浏览器将不会发送上传文件的数据。
•2、必须把form的enctype属值设为multipart/form-data.设置该值后,浏览器在上传文件时,将把文件数据附带在http请求消息体中,并使用MIME协议对上传的文件进行描述,以方便接收方对上传数据进行解析和处理。
•3、表单的提交方式要是post
如何在Servlet中读取文件上传数据,并保存到本地硬盘中?
•Request对象提供了一个getInputStream方法,通过这个方法可以读取到客户端提交过来的数据。但由于用户可能会同时上传多个文件,在servlet端编程直接读取上传数据,并分别解析出相应的文件数据是一项非常麻烦的工作,示例。
•为方便用户处理文件上传数据,Apache 开源组织提供了一个用来处理表单文件上传的一个开源组件( Commons-fileupload ),该组件性能优异,并且其API使用极其简单,可以让开发人员轻松实现web文件上传功能,因此在web开发中实现文件上传功能,通常使用Commons-fileupload组件实现。
使用Commons-fileupload组件实现文件上传,需要导入该组件相应的支撑jar包:Commons-fileupload和commons-io。commons-io 不属于文件上传组件的开发jar文件,但Commons-fileupload 组件从1.1 版本开始,它工作时需要commons-io包的支持。
代码实现:
1.首先创建一个添加书籍页面:bookAdd.jsp
页面id为photo_id的hidden标签用于存储图片路径,方便提交到后台存放到数据库,id为img_id的标签用于显示图片,所有图片都存放在服务器下,方便读取。然后一个关键js,点击button通过模式窗口弹出上传页面,在弹出模式窗口时定义了一个变量win,该变量用于获取模式窗口传回的图片路径值。
(注意:因为安全性问题图片不能图片不能随意存放,项目部署在服务器中,图片就只能放在该服务器下才能查看得到,如果一定要读取非当前服务器下的图片需要配置服务器的虚拟目录)
<html>
<head>
<title>添加书籍</title>
<script type="text/javascript">
//打开上传页面
function openUpload(){
var win = window.showModalDialog("<%=root%>/Admin/bookUpload.jsp","","dialogWidth:300px;dialogHeight:300px;scroll:no;status:no");
if(win != null){
document.getElementById("photo_id").value = win;
document.getElementById("img_id").src = "<%=root%>/"+win;
}
}
</script>
</head>
<body>
<h5>添加书籍</h5><hr/>
<p>
书的封面:
<label>
<input type="hidden" id="photo_id" name="photo" value="images/noimg.png"><input type="button" onclick="openUpload()" value="上传图片"/><br/>
<img id="img_id" alt="" src="<%=root%>/images/noimg.png" width="200px" height="200px">
</label>
</p>
</body>
</html>
(2)创建上传图片页面,bookUpload.jsp
注意一定要定义标签,当前模式窗口关闭时才能将数据返回到父窗体,标签还要设置一个属性enctype=”multipart/form-data”这样提交的文件才能被后台获取,点击“上传”button即可将文件向后台传送,剩下的重头戏就是后台上传处理了。
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
<meta http-equiv="pragma" content="no-cache" />
<span style="color: #ff0000;"><base target="_self"></span>
<title>书籍图片上传</title>
</head>
<body>
<h5>图片上传</h5><hr/>
<p style="color: red">${requestScope.errorMsg}</p>
<form id="form1" name="form1" action="<%=root%>/BookServlet?type=bookUpload" method="post" enctype="multipart/form-data">
<div>注:图片大小最大不能超过3M!</div>
<div><input type="file" name="file_upload"/></div>
<div><input type="submit" value="上传"/></div>
</form>
</body>
</html>
(3)创建一个普通的Servlet,下面只提供部分关键代码
红色代码部分是上传的关键代码,其它就是作为点缀了。完成这三步,一个简单的上传即实现了。
public class BookServlet extends HttpServlet {
private String uploadPath = "eShop/upload/"; // 上传文件的目录
private String tempPath = "eShop/uploadtmp/"; // 临时文件目录
private String serverPath = null;
private int sizeMax = 3;//图片最大上限
private String[] fileType = new String[]{".jpg",".gif",".bmp",".png",".jpeg",".ico"};
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
serverPath = getServletContext().getRealPath("/").replace("\\", "/");
//Servlet初始化时执行,如果上传文件目录不存在则自动创建
if(!new File(serverPath+uploadPath).isDirectory()){
new File(serverPath+uploadPath).mkdirs();
}
if(!new File(serverPath+tempPath).isDirectory()){
new File(serverPath+tempPath).mkdirs();
}
DiskFileItemFactory factory = new DiskFileItemFactory();</span>
factory.setSizeThreshold(5*1024); //最大缓存
factory.setRepository(new File(serverPath+tempPath));//临时文件目录
ServletFileUpload upload = new ServletFileUpload(factory);</span>
upload.setSizeMax(sizeMax*1024*1024);//文件最大上限
String filePath = null;
try {
List<FileItem> items = upload.parseRequest(request);</span>//获取所有文件列表
for (FileItem item : items) {
//获得文件名,这个文件名包括路径
if(!item.isFormField()){</span>
//文件名
String fileName = item.getName().toLowerCase();
if(fileName.endsWith(fileType[0])||fileName.endsWith(fileType[1])||fileName.endsWith(fileType[2])||fileName.endsWith(fileType[3])||fileName.endsWith(fileType[4])||fileName.endsWith(fileType[5])){
String uuid = UUID.randomUUID().toString();
filePath = serverPath+uploadPath+uuid+fileName.substring(fileName.lastIndexOf("."));
item.write(new File(filePath));</span>
PrintWriter pw = response.getWriter();
pw.write("<script>alert('上传成功');window.returnValue='"+uploadPath+uuid+fileName.substring(fileName.lastIndexOf("."))+"';window.close();</script>");
pw.flush();
pw.close();
}else{
request.setAttribute("errorMsg", "上传失败,请确认上传的文件存在并且类型是图片!");
request.getRequestDispatcher("/Admin/bookUpload.jsp").forward(request,
response);
}
}
}
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("errorMsg", "上传失败,请确认上传的文件大小不能超过"+sizeMax+"M");
request.getRequestDispatcher("/Admin/bookUpload.jsp").forward(request,
response);
}
}