java文件上传(使用commons-fileupload-1.2.1.jar和commons-io-1.3.2.jar)

文件上传,总结步骤:

<1>添加jar包,

commons-fileupload-1.2.1.jarcommons-io-1.3.2.jar

<2>写页面,写出一个form 提交

<3>写一个servlet实现文件上传程序的编写


源码:

表单页:

<form name="f1" id="f1" action="<%=path%>/servlet/UploadServlet" method="post" enctype="multipart/form-data">
      <table>
        <tr>
          <td>Title:</td>
          <td><input type="text" name="title" ></td>
        </tr>
        <tr>
          <td>File:</td>
          <td><input type="file" name="f" ></td>
        </tr> 
        <tr>
          <td colspan="2"><input type="submit" value="login"></td>
        </tr>
      </table>
    </form>

servlet的doGet()方法:

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		FileItemFactory factory=new DiskFileItemFactory();		//针对磁盘文件创建工厂
		ServletFileUpload upload=new ServletFileUpload(factory);//通过factory创建一个ServletFileUpload
		upload.setHeaderEncoding("UTF-8");//设成你的编码格式
		try {
			List items=upload.parseRequest(request);  //解析请求,获得表单上的一些选项。
			Iterator iter=items.iterator();
			while(iter.hasNext()){
				FileItem item=(FileItem)iter.next();  //取出封装成文件选项
				
				if(!item.isFormField()){		//判断一个参数域是普通的表单输入域,还是文件上传域
					String fullFileName=item.getName(); //得到要上传的文件的绝对路径
					System.out.println(fullFileName);
					int idx=fullFileName.lastIndexOf(".");//找到.的索引号
					String subfix=fullFileName.substring(idx);//截取文件全路径
					String fileName=new Date().getTime()+subfix;
					
					String path="C:/upload/";//构建上传路径
					File f=new File(path+"/");
					if (!f.exists()) {
						f.mkdirs();
					}
					try {
						item.write(new File(path+"/"+fileName));			//写入文件路径
					} catch (Exception e) {
						e.printStackTrace();
					}	
				}	
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
		}
	}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值