一、Servlet实现文件上传,需要添加第三方提供的jar包
接着把这两个jar包放到 lib文件夹下:
二:
文件上传的表单提交方式必须是POST方式,
编码类型:enctype="multipart/form-data",默认是 application/x-www-form-urlencoded
比如:<form action="FileUpLoad"enctype="multipart/form-data"method="post">
三、举例:
1.fileupload.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 ‘fileupload.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">
-
-
- </head>
-
- <body>
-
- <form action="FileUpLoad" enctype="multipart/form-data" method="post" >
-
- 用户名:<input type="text" name="usename"> <br/>
- 上传文件:<input type="file" name="file1"><br/>
- 上传文件: <input type="file" name="file2"><br/>
- <input type="submit" value="提交"/>
-
- </form>
-
-
-
- </body>
- </html>
2.实际处理文件上传的 FileUpLoad.java
System.out.println("获取上传文件的总共的容量:"+item.getSize());
3.filedemo.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 ‘filedemo.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">
-
-
- </head>
-
- <body>
-
- 用户名:${requestScope.usename } <br/>
- 文件:${requestScope.file1 }<br/>
- ${requestScope.file2 }<br/>
-
- <img alt="go" src="upload/<%=(String)request.getAttribute("file1")%> " />
-
-
-
- </body>
- </html>
4结果页面:
Servlet实现文件上传,可多文件上传
原文:http://www.cnblogs.com/hoobey/p/5294313.html