文件上传

本文详细介绍了文件上传的处理过程,包括表单提交的注意事项、IE上传的信息格式、Servlet的处理代码,以及使用Commons-fileupload库进行文件上传的实现方法。文章强调了正确配置表单和解析上传数据的重要性。

1、注意要点:

  1. 表单提交一定是post
  2. 在表单中药设置enctype=”multipart/form-data”以二进制流的方式传数据给服务器。

 2、IE上传的信息

------WebKitFormBoundaryLbE9vGVhsqQDsaaN
Content-Disposition: form-data; name="name"

wrfw
------WebKitFormBoundaryLbE9vGVhsqQDsaaN
Content-Disposition: form-data; name="text"; filename="a.txt"
Content-Type: text/plain

I am yuchao!!!
------WebKitFormBoundaryLbE9vGVhsqQDsaaN--

3、Servlet的处理代码:

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		
		InputStream in = req.getInputStream();
		byte[] bys = new byte[1000];
		int len = in.read(bys);
		String path = req.getRealPath("/upload");
		File file = new File("D:\\apache-tomcat-8.5.28\\wtpwebapps\\fileupload\\upload\\a.txt");
		OutputStream out = new FileOutputStream(file);
		BufferedOutputStream bout = new BufferedOutputStream(out);
		bout.write(bys, 0, len);
		in.close();
		bout.close();
		out.close();
		
	}

总结:如果直接提交写入文件,得到的不是上传文件的本身,需要进行单独的解析处理。有公共类库来处理这个事情。

Smartupload(过时),Apache下的Commons-fileupload来处理

 

4、使用Commons-fileupload来实现文件上传

导入Commons-fileupload.jar和Commons-io.jar

Servlet处理代码

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		//创建磁盘文件工厂
		FileItemFactory fif = new DiskFileItemFactory();
		//文件上传处理
		ServletFileUpload sf = new ServletFileUpload(fif);
		try {
			List<FileItem> list = sf.parseRequest(req);
			String path = req.getRealPath("/upload");
			for(FileItem fil:list) {
				if(fil.isFormField()) {
					System.out.println(fil.getFieldName()+"-----"+fil.getName()+"-----"+fil.getString("utf-8"));
				} else {
					String f = UUID.randomUUID()+fil.getName().substring(fil.getName().lastIndexOf("."));
					fil.write(new File(path,f));
				}
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值