1.浏览器端:选择图片、提交表单,同时将图片发送给服务器 <form action=”” method=”post” enctype=”multipart/form-data”> <input type=”file” name=”image”> <input type=”submit”> 上传的内容,都在请求体中。 2.服务器端: 1)手动获得请求体,需要手动解析。request.getInputStream() 2)使用servlet3.0 3)第三方工具 – apache-commons-fileupload 4)struts2

@WebServlet("/FileUploadServlet")
@MultipartConfig		//表示支持文件上传,否则获得null

public class FileUploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
   
protected void doGet(HttpServletRequest request, HttpServletResponse response) 
		throws ServletException, IOException {
	//1 普通字段
	String username = request.getParameter("username");
	System.out.println(username);
	
	//2 上传字段
	Part part = request.getPart("image");
	//2.1 获得文件名   
	// * IE 		--> C:\Users\liangtong\Desktop\heima.txt
	// * 其他浏览器 	--> heima.txt
	String contentDisposition = part.getHeader("Content-Disposition");
	System.out.println(contentDisposition);
	// * 截取文件名
	int start = contentDisposition.indexOf("filename=") + 10;
	int end = contentDisposition.length() - 1;
	String fileName = contentDisposition.substring(start, end);
	
	// * 浏览器兼容  -- lastIndexOf() 如果没有获得返回 -1
	fileName = fileName.substring( fileName.lastIndexOf("\\") + 1);
	
	System.out.println(fileName);
	
	//2.2 获得上传文件内容
	InputStream is = part.getInputStream();
	
	//2.3 将流写入到服务器文件中
	// * 上传目录
	String dir = this.getServletContext().getRealPath("/WEB-INF/upload");
	File file = new File(dir , fileName);
	
	// * 流的对拷
	FileOutputStream out = new FileOutputStream(file);
	
	byte[] buf = new byte[1024];
	int len = -1;
	while( (len = is.read(buf)) != -1 ){
		out.write(buf, 0, len);
	}
	
	out.close();
	is.close();
	
	
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) 
		throws ServletException, IOException {
	doGet(request, response);
}