文件上传
1.导入jar包 (在WEB-INF下的lib中添加)
commons-fileupload-1.3.3.jar
commons-io-2.6.jar
网址:http://commons.apache.org/fileupload 下载commons-fileupload-1.3.3-bin.zip
http://commons.apache.org/io 下载 commons-io-2.6.bin.zip
2.先创建登录页面login.jsp 在jsp页面添加(把所需要的类库导进jsp页面中)
<%@ page import="org.apache.commons.fileupload.*" %>
1 <%@ page language="java" contentType="text/html; charset=UTF-8"
2 pageEncoding="UTF-8"%>
3 <%@ page import="org.apache.commons.fileupload.*" %>
4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
5 <html>
6 <head>
7 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
8 <title>文件上传</title>
9 </head>
10 <body>
11 <!--把表单提交到servlet Fileupload -->
12 <form action="${pageContext.request.contextPath }/Fileupload" enctype="multipart/form-data" method="post">
13
14 <p>姓名:<input type="text" name=user></p>
15 <p>选择 图片:<input type="file" name="nfile"></p>
16 <p><input type="submit" value="提交"></p>
17 </form>
18 </body>
19 </html>
3.创建servlet类 Fileupload
//防止乱码 request.setCharacterEncoding("UTF-8"); String name=""; //上传的名字 String filename=""; //表单元素的name属性 //创建FileItemFactory 和ServletFileUpload 对象 FileItemFactory factory= new DiskFileItemFactory(); ServletFileUpload upload=new ServletFileUpload(factory); try { //解析form表单所有文件 List<FileItem> items=upload.parseRequest(request); Iterator<FileItem> iterator=items.iterator(); //循环判定当前FileItem是普通表单元素,还是文件域 while (iterator.hasNext()) { //以此处理每个文件 FileItem next = iterator.next(); if (next.isFormField()) { //普通表单字段 filename=next.getFieldName(); //表单字段的name属性 if (filename.equals("user")) {
request.setAttribute("name",next.getString("utf-8")); } }else { //文件表单字段 //在webcontext下创建的文件夹 存放你想上传的文件或图片 String rootpath=this.getServletContext().getRealPath("upload/"); filename=next.getName(); if(filename!=null&&!filename.equals("")){ File fullFile=new File(next.getName()); File saveFile=new File(rootpath, fullFile.getName()); next.write(saveFile); request.setAttribute("result", "上传成功!"); //上传文件的名称 request.setAttribute("file",filename ); } } } } catch (Exception e) { e.printStackTrace(); } request.getRequestDispatcher("/sussce.jsp").forward(request,response);
4.创建上传成功页面 sussce.jsp (本次上传的为图片)
1 <%@ page language="java" contentType="text/html; charset=UTF-8"
2 pageEncoding="UTF-8"%>
3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
4 <html>
5 <head>
6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
7 <title>上传图片</title>
8 </head>
9 <body>
10 <%=request.getAttribute("result") %>
11 <%=request.getAttribute("name") %>
12 <img alt="图片" src="<%=request.getAttribute("file") %>">
13 </body>
14 </html>