upload.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
  </head>
  
  <body>
  <!-- 表单提交必须为post ,  get会把表单数据放到地址栏,地址栏最多放4kb左右的大小 -->
  
    <form action="UploadServlet"  method="post" enctype="multipart/form-data">
    	<!--  学号: <input type="text" name="sno" /><br/>
    	姓名: <input type="text" name="sname" /><br/>-->
    	上传照片: <input type="file" name="spicture"  />
    	<br>
    	<input type="submit" value="提交"/>
    </form>
    <p>${informations}</p>
    <!--  <a href="DownloadServlet?filename=图片.jpg">图片</a>  -->
  </body>
</html>

UoloadServlet

 

package servlet;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class UploadServlet
 */
public class UploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    
    public UploadServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

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

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=UTF-8");
		try {
			boolean isMultipart = ServletFileUpload.isMultipartContent(request);
			if( isMultipart ){
//				FileItemFactory factory = new DiskFileItemFactory();
				DiskFileItemFactory factory = new DiskFileItemFactory();
				ServletFileUpload upload = new ServletFileUpload(factory);
				String path1 = request.getContextPath();
				String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path1+"/";
				upload.setSizeMax(20480000);  //20000KB  字节B
				List<FileItem> items = upload.parseRequest(request);
				Iterator<FileItem> iter= items.iterator();
				while(iter.hasNext()){
					FileItem item = iter.next();
					String itemName = item.getFieldName();
					int sno = -1;
					String sname = null;
					
					if(item.isFormField()){
						
					}else {
						//文件上传
						//先拿文件名  getFieldname是获取普通表单字段的name值  
						//getName() 是获取文件名
						String fileName = item.getName();    //a.txt  a.docx  a.png
						String ext = fileName.substring(fileName.indexOf(".")+1);
						if(!(ext.equals("png") || ext.equals("gif") || ext.equals("jpg"))){
							System.out.println("图片类型有误!格式只能是png gif jpg");
							request.setAttribute("informations", "图片类型错误"); 
							request.getRequestDispatcher("/daoyuan/upload.jsp").forward(request, response);
							return ;  // 终止
						}
						//获取文件内容并上传
						//定义文件路径 ;制定上传位置
						/*获取服务器路径"D:\\"\\\*/
						//String path = request.getSession().getServletContext().getRealPath("/res");
						String path = request.getSession().getServletContext().getRealPath("/daoyuan/images");
						File file = new File(path , fileName); 
						item.write(file);//上传
						System.out.println(fileName+"上传成功");
//						File fileexiset = new File("path/fileName");
//						if(fileexiset.exists()){
//						}
						request.setAttribute("informations", "上传成功"); 
						request.getRequestDispatcher("/daoyuan/upload.jsp").forward(request, response);
						return;
					}
				}
			}
		} catch (FileUploadBase.SizeLimitExceededException e){
			System.out.println("上传文件大小超过限制!! 最大20000KB");
		}catch (FileUploadException e) {
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

####如果是Servlet2.5    ----》》》记得在web.xml里边配置一下

####如果是Servlet3.0  ----->>>>>直接使用注解就可以啦