commons-fileupload实现文件上传功能实例

Apache提供的commons-fileupload jar包实现文件上传确实很简单,最近要用Servlet/JSP做一个图片上传功能,在网上找了很多资料,大多是基于struts框架介绍的,

还有些虽然也介绍common-fileupload的上传,但是那些例子比较老,有些类现在都废弃了。

 
 

案例场景

一个图书馆后台管理界面,需要提供上传图书图片的功能并且最终显示在页面中。

实现效果

进入添加书籍页面,默认显示一个图片“暂无图片”(长宽均为200px),提供一个按钮“上传图片”,如下图效果。


点击“上传图片”按钮,通过模式窗口弹出上传界面,如下图所示。

通过“浏览”按钮选择指定图片,点击“上传”按钮进行上传,如果上传成功则弹出成功提示,

用户点击“确定”后关闭弹出窗并自动将新图片显示在页面上,如下图所示。


代码实现

①首先创建一个添加书籍页面:bookAdd.jsp

页面id为photo_id的hidden标签用于存储图片路径,方便提交到后台存放到数据库,

id为img_id的<img>标签用于显示图片,所有图片都存放在服务器下,方便读取。

然后一个关键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" οnclick="openUpload()" value="上传图片"/><br/>
					<img id="img_id" alt="" src="<%=root%>/images/noimg.png" width="200px" height="200px">
				</label>
			</p>
      </body>
</html>

②创建上传图片页面,bookUpload.jsp

注意一定要定义<base>标签,当前模式窗口关闭时才能将数据返回到父窗体,

<form>标签还要设置一个属性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>

③创建一个普通的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();
		factory.setSizeThreshold(5*1024); //最大缓存
		factory.setRepository(new File(serverPath+tempPath));//临时文件目录
		
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setSizeMax(sizeMax*1024*1024);//文件最大上限
		
		String filePath = null;
		try {
			List<FileItem> items = upload.parseRequest(request);//获取所有文件列表
			for (FileItem item : items) {
				//获得文件名,这个文件名包括路径
				if(!item.isFormField()){
					//文件名
					String fileName = item.getName().toLowerCase();
					
					if(fileName.endsWith(fileType[0])||fileName.endsWith(fileType[1])
<span style="white-space:pre">							</span>||fileName.endsWith(fileType[2])||fileName.endsWith(fileType[3])
<span style="white-space:pre">							</span>||fileName.endsWith(fileType[4])
<span style="white-space:pre">							</span>||fileName.endsWith(fileType[5])){
						String uuid = UUID.randomUUID().toString();
						filePath = serverPath+uploadPath+uuid+fileName.substring(fileName.lastIndexOf("."));
						item.write(new File(filePath));
						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);
		}
		
	}

































  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值