文件上传问题汇总

网页文件上传

  网页中要求做一个文件上传,一脸蒙逼的我准备把遇到的问题记录下来,由于我是网页设计中小白中的小白,所以可以说是处处都是坑。

1.HTML需要做的事

  实现文件上传最基本也是最原始的方法便是用form表单提交,需要的只是指定一下提交数据的编码格式。

<form method="post" action="submitEntrust" enctype="multipart/form-data">

      默认情况下,enctype的值是application/x-www-form-urlencoded,不能用于文件上传;只有使用了multipart/form-data,才能完整的传递文件数据。

  另外可以一个输入框中选择多个文件进行上传,这需要设置 multiple属性。

<input type="file" name="1" multiple="multiple">

  

2.servlet需要做的事

  利用commons-fileupload组件简化文件上传,需要在lib目录下放入两个jar文件。

  

public class FileUpload extends HttpServlet {
		//用于存放上传文件的目录
		private String uploadPath = "D:\\addnetFile\\"; 
		//用于存放临时文件的目录
		private File tempPath =new File("C:\\windows\\temp\\"); 
		 /**
		  * 初始化Servlet,确保需要使用的目录都被建立. <br>
		  * @throws ServletException if an error occure
		  */
		 public void init() throws ServletException {
		 	if(!new File(uploadPath).isDirectory())
		 		new File(uploadPath).mkdir();
		 	if(!tempPath.isDirectory()){
		 		tempPath.mkdir();
		 	}
		 }
		/**
		  * 销毁servlet. <br>
		  */
		 public void destroy() {
		 	super.destroy();
		 	}
	 /**
	  * servlet的doPost方法. <br>
	  *
	  *下面的注释是方法参数的信息.
	  *
	  * @param request the request send by the client to the server
	  * @param response the response send by the server to the client
	  * @throws ServletException if an error occurred
	  * @throws IOException if an error occurred
	  */
	  public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{
	  	res.setContentType("text/html; charset=GB2312");
	  	PrintWriter out=res.getWriter();
	  	System.out.println(req.getContentLength());
	  	System.out.println(req.getContentType());
	   
	  	DiskFileItemFactory factory = new DiskFileItemFactory();
	  	// 缓存数据的大小
	  	factory.setSizeThreshold(4096);
	  	// 临时文件保存的位置
	   factory.setRepository(tempPath);
	   
	   ServletFileUpload upload = new ServletFileUpload(factory);
	   //可以上传的文件的最大字节数,如果文件太大会抛出异常
	   upload.setSizeMax(1000000);
	   	List fileItems = null;
		try {
			//开始读取上传信息
			fileItems = upload.parseRequest(req);
			//依次处理每个上传的文件
			Iterator iter = fileItems.iterator();
			// 正则匹配,过滤路径取文件名
			String regExp=".+\\\\(.+)$";
			//过滤掉的文件类型
			String[] errorType={".exe",".com",".cgi",".asp"};
			Pattern p = Pattern.compile(regExp);
			while (iter.hasNext()) {
				FileItem item = (FileItem)iter.next();
				//忽略其他不是文件域的所有表单信息
				if (!item.isFormField()) {
					String name = item.getName();
					long size = item.getSize();
					if((name==null||name.equals("")) && size==0)
	                 continue;
					Matcher m = p.matcher(name);
					boolean result = m.find();
					//如果是允许上传的文件类型,就进行上传操作
					if (result){
						for (int temp=0;temp<errorType.length;temp++){
							if (m.group(1).endsWith(errorType[temp])){
								throw new IOException(name+": wrong type");
								}
							}
						try{
							//保存上传的文件到指定的目录
							//在下文中上传文件至数据库时,将对这里改写
							item.write(new File(uploadPath,m.group(1)));
							out.print(name+"  "+size+"<br>");
							}catch(Exception e){
								out.println("333"+e);
								}
							}
	               else
	               {
	                 throw new IOException("fail to upload");
	               }
	               }
	           }
	        }catch (IOException e){
	           out.println("222"+e);
	         }catch (FileUploadException e1) {
				e1.printStackTrace();
				out.println("111"+e1);
			}
	    }
}

  

  其中java的目录创建需要利用mkdir()和mkdirs(),l两者区别是前者只能创建一级目录,比如在文件夹a下创建文件夹b;后者可以一次性创建多级目录,如在文件夹a下创建文件夹b,在文件夹b下创建文件夹c.

    File file = new File("路径");//此时file在内存中
    File dir = file.getParentFile();   //获取file上级目录
    if(!dir.exists())   //上级目录不存在
        dir.mkdirs();    //创建多级写入外存
			
		
		

  

posted @ 2017-05-05 14:21  阿柒~  阅读(182)  评论(0编辑  收藏  举报