Servlet文件上传的实现

1.常用的三个文件上传组件:apache commons-upload,Orialiy – COS – 2008() ;smart-upload
2.使用commons-upload开发文件上传功能
1).下载commons-upload的jar包及依赖包;并添加到项目工程中
2).修改html的form表单,设置表单的内容编码类型为:multipart/form-date
3).编写jsp或servlet处理文件上传,和其他表单数据
在webContent目录下,创建一个目录用于保存上传后的文件

4).保存文件在服务器的路径

代码实现:

 jsp页面:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
		<!-- 进行文件上传,必须把enctype修改为multipart/form-date -->
		<form name="regForm" action="upLoadServlet"  method="post" enctype="multipart/form-data">
			<table width="500" align="center" border="1">
				<tr>
					<td colspan="2">用户注册</td>
				</tr>
				<tr>
					<td>账号</td>
					<td><input name="userName" type="text"></td>
				</tr>
				<tr>
					<td>密码</td>
					<td><input name="password" type="password"></td>
				</tr>
				<tr>
					<td>头像</td>
					<td><input name="userHead" type="file"></td>
				</tr>				
				<tr>
					<td><input type="submit"></td>
					<td><input type="reset"></td>
				</tr>		
			</table>
			
		</form>
		
</body>
</html>
效果:

upLoadServlet:

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		UserInfo userInfo=new UserInfo();//使用临时变量保存用户上传后的数据
		//1.对上传的文件进行归类管理
		//获取Uploads在文件系统中的路径
		String basePath=getServletContext().getRealPath("/uploads");
		String tempPath=getServletContext().getRealPath("/temp");
		Calendar calendar=Calendar.getInstance(Locale.CHINA);
		
		String subPath=calendar.get(Calendar.YEAR)+"/"+calendar.get((Calendar.MONTH)+1);
		System.out.println(basePath+"/"+subPath);
		File file=new File(basePath+"/"+subPath);
		if(!file.exists()){
			file.mkdirs();//创建多级目录,根据日期变化创建不同的文件目录分类保存文件
		}
		File file2=new File(tempPath);
		if(!file2.exists()){
			file.mkdirs();//如果没有改目录则创建
		}	
		
		
		//2.文件上传的处理
		//文件项工厂类
		DiskFileItemFactory factory = new DiskFileItemFactory();  
        factory.setSizeThreshold(5*1024); //最大缓存    
        factory.setRepository(new File(tempPath));//临时文件目录    
        //设置上传参数
        ServletFileUpload upload = new ServletFileUpload(factory);  
        upload.setSizeMax(5*1024*1024);//文件最大上限   
        
		try {
			List<FileItem>items=upload.parseRequest(request);
			for(FileItem fileItem:items){
				if(fileItem.isFormField()){
					//文本域处理
					String filedName=fileItem.getFieldName();
					System.out.println(filedName);
					String value=fileItem.getString();
					String str=new String(value.getBytes(Charset.forName("ISO-8859-1")),"UTF-8");
					if("userName".equals(filedName)){
						System.out.println("userName=="+str);
						userInfo.setUserName(str);
					}else if ("password".equals(filedName)) {
						System.out.println("password=="+str);
						userInfo.setPassword(str);
					}
				}else {
					//文件处理
					//防止未上传文件时发生异常
					if(fileItem.getName()!=null&&fileItem.getName().trim().length()>3){
					
					String fileName=fileItem.getName().toLowerCase();//把文件名统一转换成小写
					int beginIndex=fileName.lastIndexOf(".");
					if(beginIndex!=-1){
					System.out.println(beginIndex);
					String fileType=fileName.substring(beginIndex);
					System.out.println("fileType"+fileType);
					//服务器重命名时使用UUID算法生成一个随机文件名,用于重命名,上传后的文件
					String randomFileName=UUID.randomUUID().toString().toLowerCase()+fileType;
					System.out.println("randomFileName:"+randomFileName);
					
					File uploadFile=new File(basePath+"/"+subPath,randomFileName);
					System.out.println("uploadFile"+uploadFile.getAbsolutePath());
					fileItem.write(uploadFile);//执行上传		
					
					userInfo.setUserHead("uploads/"+subPath+"/"+randomFileName);
					System.out.println("相对路径:  "+userInfo.getUserHead());
					fileItem.delete();//文件上传成功,删除临时文件
					
					//本例把数据传递到success页面进行保存处理
					request.getSession().setAttribute("userInfo", userInfo);
					//3.对上传后的路径进行保存或处理
					response.sendRedirect("success.jsp");
				
					}
				}else {
					response.sendRedirect("Upload.jsp");
				}
				}
			}
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();

效果演示:

文件读取通过EL表达式进行读取

头像:<img src="${ userInfo.userHead}" width="100px">  在设置图片大小时不能同时设置宽高,否则失真

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值