Servlet 文件上传, HttpServletRequestWrapper

  • Post author:
  • Post category:其他


需要使用一些jar包。commons-fileupload-1.2.2.jarcommons-io-1.4.jar

<form action="FileUpload" enctype="multipart/form-data" method="post">
  		<input type="text" name="name"><br>
  		<input type="file" name="fileName"><br>
  		<input type="submit">
  	</form> 

这情况下,因为服务器获得是输入流,是得不到name的值的。

System.out.println(request.getParameter(“name”)); //null

System.out.println(request.getParameter(“fileName”)); //null

public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		
		System.out.println(request.getParameter("name"));
		System.out.println(request.getParameter("fileName"));

		ServletFileUpload upload = new ServletFileUpload();
		
		
		try {
			FileItemIterator iter = upload.getItemIterator(request);
			while(iter.hasNext()){
				FileItemStream item = iter.next();
				String name = item.getFieldName();
				
				//得到表单域,是一个输入流
				InputStream stream = item.openStream();
				
				//如果是普通表单域
				if(item.isFormField()){
					String value = Streams.asString(stream);
					System.out.println(name + " -> " + value);
				}else{
					String filename = item.getName(); //得到文件上传名
					System.out.println("文件:" + filename);
				}
			}
			
		} catch (FileUploadException e) {
			e.printStackTrace();
		}
		
		System.out.println(request.getInputStream().available());;
		out.flush();
		out.close();
	}

null

null

name -> fdsf

文件:hello.zip

0

正常上传的话,可以用:

Streams.copy(stream, new FileOutputStream(request.getRealPath(“upload”)+”\\” + filename), true);

System.out.println(“cpy: ” + request.getRealPath(“upload”) + filename);