使用commons-fileupload实现文件上传

1、先声明一个实体类用于临时数据的保存UserInfo

package tt{
public class UserInfo {
	private String uname;
	private String upass;
	private String uhead;
		
	public UserInfo() {
		super();
	}

	public UserInfo(String uname, String upass, String uhead) {
		super();
		this.uname = uname;
		this.upass = upass;
		this.uhead = uhead;
	}

	public String getUname() {
		return uname;
	}

	public void setUname(String uname) {
		this.uname = uname;
	}

	public String getUpass() {
		return upass;
	}

	public void setUpass(String upass) {
		this.upass = upass;
	}

	public String getUhead() {
		return uhead;
	}

	public void setUhead(String uhead) {
		this.uhead = uhead;
	}
}
2、写一个简单的表单

<form name="regForm" action="UploadServlet" method="post" enctype="multipart/form-data" >
		<table width="400" align="center" border="1" margin-top="50%">
			<tr>
				<td colspan="2" >用户注册</td>					
			</tr>
			<tr>
				<td>账号:</td>
				<td><input name="uname" type="text"></td>		
			</tr>
			<tr>
				<td>密码:</td>
				<td><input name="upass" type="password"></td>		
			</tr>
			<tr>
				<td>头像:</td>
				<td><input name="uhead" type="file"></td>		
			</tr>
			<tr>
				<td><input type="submit"  value="提交"></td>
				<td><input type="reset"></td>		
			</tr>
		</table>	
	</form>
<!--进行文件上传,必须把enctype声明为multipart/form/data-->
3、servlet部分
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//使用临时变量保存上传后的数据
		UserInfo userInfo=new UserInfo();
		
		//1.对上传的文件进行归类管理
		//获取uploads在文件系统中的路径
		String basePath=getServletContext().getRealPath("/uploads");//上传后的保存文件的目录
		String tempPath=getServletContext().getRealPath("/temp");//上传过程中临时缓存的目录
		
		Calendar calender=Calendar.getInstance(Locale.CHINA);
		String subPath=calender.get(Calendar.YEAR)+"/"+(calender.get(Calendar.MONTH)+1);
		System.out.println(basePath+"/"+subPath);
		File file1 = new File(basePath+"/"+subPath);
		File file2 = new File(tempPath);
		if(!file1.exists()){
			file1.mkdirs();//根据日期变化创建不同的文件目录分类保存
		}	
		//缓存目录
		
		if(!file2.exists()){
			file2.mkdirs();
		}
		//2.文件上传处理
		//使用commons-upload进行上传,设置上传参数
		 DiskFileItemFactory factory = new DiskFileItemFactory();  
	        factory.setSizeThreshold(5*1024); //最大缓存    
	        factory.setRepository(new File(tempPath));//临时文件目录    
	            
	        ServletFileUpload upload = new ServletFileUpload(factory);  
	        upload.setSizeMax(5*1024*1024);//文件最大上限  1024是一个字节1024*1024就是1M
	        
	     try {
			List<FileItem> items=upload.parseRequest(request);//获取所有文件列表
			
			for(FileItem fileItem:items){
				if(fileItem.isFormField()){//判断是否为文件
					//2.2 文本域的处理
					String fieldName=fileItem.getFieldName();
					String value=fileItem.getString();
					String s=new String (value.getBytes(Charset.forName("ISO-8859-1")),"UTF-8");
					if("uname".equals(fieldName)){						
						System.out.println("uname=="+s);
						userInfo.setUname(s);//保存账号信息到临时的用户对象中
					}else if("upass".equals(fieldName)){
						System.out.println("upass=="+s);
						userInfo.setUpass(s);//保存密码信息到临时的用户对象中
					}	
				}else{
					if(fileItem.getName()!=null && fileItem.getName().trim().length()>0){
						//2.1 文件处理
						String fileName=fileItem.getName().toLowerCase();//把文件名统一转换成小写
						int beginInsex=fileName.lastIndexOf(".");
						String fileType=fileName.substring(beginInsex);
						System.out.println("fileType"+fileType);
						
						//使用UUID算法生成一个随机文件名,用于重命名上传后的文件
						String radomFileName=UUID.randomUUID().toString().toLowerCase()+fileType;
						System.out.println("radomFileName"+radomFileName);
						
						//上传后的文件在服务器中的绝对路径,包含文件名称
						File uploadFile=new File(basePath+"/"+subPath,radomFileName);
						System.out.println("uploadFile"+uploadFile);
						fileItem.write(uploadFile);//执行上传
						
						//计算爆粗到数据库的文件- 相对路径,并保存到临时用户对象中
						//相对路径是相对于网站的根路径进行计算的,相对于webContent
						userInfo.setUhead("uploads/"+subPath+"/"+radomFileName);
						System.out.println(userInfo.getUhead());
						
						fileItem.delete();//文件上传成功,删除临时成功
					}
				}
			}						
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}				
		//3.对上传后的文件的路径进行保存或处理
		//本例,把数据喘息道success页面进行显示
	     request.getSession().setAttribute("user", userInfo);
		response.sendRedirect("success.jsp");											
	}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值