您的位置:首页 > 其它

使用common upload实现文件上传

2014-05-03 09:48 337 查看
后台进行文件上传的页面:

<body><div  style="text-align: left;"><br/><br/><br/><center>
     <form action="FileUploadServlet" enctype="multipart/form-data" method="post">
     <div style="margin-left:100px;">请选择文件:<input type="file" name="file1"><br><br/></div>	 
     	   上传者:<input type="text" name="uperson"/><br/><br/>  
     	  上传时间:<input type="date" name="utime"/> <br/><br/>
     	  文件描述:<input type="text" name="ufiledescr"/><br/><br/>
        <input type="submit"  name="submit" value="上传">    <input type="reset" name="reset" value="重置"/>
    </form></center></div>
  </body>


FileUploadServlet的处理代码:

public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {	
	
		   response.setContentType("text/html; charset=utf-8");
		   request.setCharacterEncoding("utf-8");//防止中文名乱码
			PrintWriter out=response.getWriter();
	        int sizeThreshold=1024*6; //缓存区大小
	        System.out.println(getServletContext().getRealPath("/upload/"));
	        String basePath = this.getServletContext().getRealPath("/upload/");
	        File repository = new File(basePath); //缓存区目录
	        long sizeMax = 1024 * 1024 * 200;//设置文件的大小为200M
	        final String allowExtNames = "jpg,gif,bmp,rar,rar,txt,docx,ppt";
	        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
	        diskFileItemFactory.setRepository(repository);
	        diskFileItemFactory.setSizeThreshold(sizeThreshold);
	        ServletFileUpload servletFileUpload=new ServletFileUpload(diskFileItemFactory);
	        servletFileUpload.setSizeMax(sizeMax);

	        int i=0;//用于保存表单属性的值
	        String[] contents=new String[5];
	        
	        if(basePath==null){
	        	out.print("无法访问存储目录");
	        	return;
	        }
	        File fUploadDir=new File(basePath);
	        if(!fUploadDir.exists()){
	        		if(!fUploadDir.mkdir()){
	        			out.print("无法创建存储目录");
	        			return;
	        		}
	        }
	        if(!DiskFileUpload.isMultipartContent(request)){
	        	out.println("只能处理multipart/form-data类型的数据");
	        	return;
	        }
	        List<FileItem> fileItems = null;
	        try{
	            fileItems = servletFileUpload.parseRequest(request);
	            
	        }catch(FileUploadException e){
	        		out.print("解析数据的时候出现如下问题:");
	        		e.printStackTrace();	
	        		return ;
	        	
	        }
	        
	            //处理每个表单字段
	            Iterator it=fileItems.iterator();
	            while(it.hasNext()){
	            	FileItem fi=(FileItem)it.next();
	            	if(fi.isFormField()){//普通表单属性
	            		String content=fi.getString("utf-8");//表单属性的值
	            		String fieldName=fi.getFieldName();//表单属性的名字
	            		contents[i++]=content;
	            	/*	if(content.equals("")){
	            				out.print("<br><br><br><center><h3>请填写完整!</h3><a href=javascript:history.go(-1)>返回</a></center>");
	            						return;
	            		}
	            		*/
	            	}else{//处理表单中为文件属性
	            		try{
	            			String pathSrc=fi.getName();//得到文件的路径名,比如d:\\tomcat6\\upload\001.doc
	            			if(pathSrc.trim().equals("")){//用户没有选择文件,则忽略对该字段的处理
	            				continue;
	            			}
	            			int start=pathSrc.lastIndexOf("\\");
	            			String fileName=pathSrc.substring(start+1);
	            			File pathDest=new File(basePath,fileName);
	            			fi.write(pathDest);
	            			contents[4]=fileName;
	            			/*String fieldName=fi.getFieldName();
	            			request.setAttribute(fieldName,fileName);*/
	            		}catch(Exception e){
	            			out.print("存储文件时出现异常");
	            			e.printStackTrace();
	            			return;
	            		}
	            	}
	            }
	            
	            	FileUploadBean fub=new FileUploadBean();
	            	fub.setUperson(contents[0]);
	            	fub.setUtime(contents[1]);
	            	fub.setUfiledescr(contents[2]);
	            	fub.setFilename(contents[4]);
	            	
	            	FileUploadDao fd=new FileUploadDaoImpl();
	            	int result=fd.save(fub);
	            	if(result==1){
	            		out.print("<br><br><br><center><h3>上传成功!</h3><a href=javascript:history.go(-1)>返回</a></center>");
	            	}else{
	            		out.print("<br><br><br><center><h3>上传失败!</h3><a href=javascript:history.go(-1)>返回</a></center>");
	            	}
	}


FileUploadDaoImpl的实现代码:

public int save(FileUploadBean f) {
		sql="insert into uploadfile(uperson,utime,filename,ufiledescr) values(?,?,?,?)";
		try{
			conn=DbUtil.getConn();
			ps=DbUtil.getPreparedStatement(conn, sql);
			ps.setString(1,f.getUperson());
			ps.setString(2,f.getUtime());
			ps.setString(3,f.getFilename() );
			ps.setString(4, f.getUfiledescr());
			int result=ps.executeUpdate();
			if(result==1){
				return 1;
			}
		}catch(SQLException e){
			e.printStackTrace();
		}finally{
			DbUtil.closePs(ps);
			DbUtil.closeConn(conn);
		}
			return 0;
	}


另外,在相应的目录下有upload文件夹才行。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: