先上图,这是一个用MyEclipse写的文件上传和下载。
下图是上传的界面,点击按钮可以选择文件。(页面比较丑,勿喷)
下图是上传多个文件,点击“单击此处添加更多文件”,则会出现多个按钮,选择多个文件,不需要时移除即可。
点击提交后,就会跳转到下图,下载列表,会显示上传的文件。
点击相应的文件名,即可下载。(下图左下角即为我下载的图片)
下图是项目相关文件。
接下来就是上代码了。
第一个页面:upload1.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 'Upload1.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">
<style type="text/css">
.button:nth-child(6n){
margin-right: 0;
}
.button.gray{
color: #8c96a0;
text-shadow:1px 1px 1px #fff;
border:1px solid #dce1e6;
box-shadow: 0 1px 2px #fff inset,0 -1px 0 #a8abae inset;
background: -webkit-linear-gradient(top,#f2f3f7,#e4e8ec);
background: -moz-linear-gradient(top,#f2f3f7,#e4e8ec);
background: linear-gradient(top,#f2f3f7,#e4e8ec);
}
.round,
.side,
.tags{
padding-right: 30px;
}
.round:after{
position: absolute;
display: inline-block;
content: "\003c";
top:50%;
right:10px;
margin-top: -10px;
width: 17px;
height: 20px;
padding-left: 3px;
line-height:18px;
font-size: 10px;
font-weight: normal;
border-radius: 10px;
text-shadow:-2px 0 1px #333;
-webkit-transform:rotate(-90deg);
-moz-transform:rotate(-90deg);
transform:rotate(-90deg);
}
.gray.round:after{
box-shadow:1px 0 1px rgba(255,255,255,1) inset,1px 0 1px rgba(0,0,0,.2);
background:-webkit-linear-gradient(top,#dce1e6,#dde2e7);
background:-moz-linear-gradient(top,#dce1e6,#dde2e7);
background:linear-gradient(top,#dce1e6,#dde2e7);
text-shadow:-2px 0 1px #fff;
}
.side:after{
position: absolute;
display: inline-block;
content: "\00bb";
top:3px;
right:-4px;
width: 38px;
height:30px;
font-weight: normal;
line-height: 26px;
border-radius:0 0 5px 5px;
text-shadow:-2px 0 1px #333;
-webkit-transform:rotate(-90deg);
-moz-transform:rotate(-90deg);
transform:rotate(-90deg);
}
.gray.side:after{
text-shadow:-2px 0 1px #fff;
border-top: 1px solid #d4d4d4;
box-shadow:-2px 0 1px #eceef1 inset;
background:-webkit-linear-gradient(right,#e1e6ea,#f2f2f6 60%);
background:-moz-linear-gradient(right,#e1e6ea,#f2f2f6 60%);
background:linear-gradient(right,#e1e6ea,#f2f2f6 60%);
}
.tags:after{
font-weight: normal;
position: absolute;
display: inline-block;
content: "FREE";
top:-3px;
right: -33px;
color: #fff;
text-shadow:none;
width: 85px;
height:25px;
line-height: 28px;
-webkit-transform:rotate(45deg) scale(.7,.7);
-moz-transform:rotate(45deg) scale(.7,.7);
transform:rotate(45deg) scale(.7,.7);
}
.gray.tags:after{
background: #8c96a0;
border:2px solid #fff;
}
.button.rarrow,
.button.larrow{
overflow:visible;
}
.rarrow:after,
.rarrow:before,
.larrow:after,
.larrow:before{
position:absolute;
content: "";
display: block;
width: 28px;
height: 28px;
-webkit-transform:rotate(45deg);
-moz-transform:rotate(45deg);
transform:rotate(45deg);
}
.rarrow:before{
width: 27px;
height: 27px;
top: 6px;
right: -13px;
clip: rect(auto auto 26px 2px);
}
.rarrow:after{
top: 6px;
right: -12px;
clip: rect(auto auto 26px 2px);
}
.gray.rarrow:before{
background: #d6dbe0;
}
.gray.rarrow:after{
box-shadow: 0 1px 0 #fff inset,-1px 0 0 #b7babd inset;
background:-webkit-linear-gradient(top left,#f2f3f7,#e4e8ec);
background:-moz-linear-gradient(top left,#f2f3f7,#e4e8ec);
background:linear-gradient(top left,#f2f3f7,#e4e8ec);
}
.larrow:before{
top: 6px;
left: -13px;
width: 27px;
height: 27px;
clip: rect(2px 26px auto auto);
}
.larrow:after{
top: 6px;
left: -12px;
clip: rect(2px 26px auto auto);
}
.gray.larrow:before{
background: #d6dbe0;
}
.gray.larrow:after{
box-shadow: 0 -1px 0 #b7babd inset,1px 0 0 #fff inset;
background:-webkit-linear-gradient(top left,#f2f3f7,#e4e8ec);
background:-moz-linear-gradient(top left,#f2f3f7,#e4e8ec);
background:linear-gradient(top left,#f2f3f7,#e4e8ec);
}
.gray:hover{
background: -webkit-linear-gradient(top,#fefefe,#ebeced);
background: -moz-linear-gradient(top,#f2f3f7,#ebeced);
background: linear-gradient(top,#f2f3f7,#ebeced);
}
.gray:active{
top:1px;
box-shadow: 0 1px 3px #a8abae inset,0 3px 0 #fff;
background: -webkit-linear-gradient(top,#e4e8ec,#e4e8ec);
background: -moz-linear-gradient(top,#e4e8ec,#e4e8ec);
background: linear-gradient(top,#e4e8ec,#e4e8ec);
}
.gray.side:hover:after{
background:-webkit-linear-gradient(right,#e7ebee,#f8f8f8 60%);
background:-moz-linear-gradient(right,#e7ebee,#f8f8f8 60%);
background:linear-gradient(right,#e7ebee,#f8f8f8 60%);
}
.gray.side:active:after{
top:4px;
border-top: 1px solid #9fa6ab;
box-shadow:-1px 0 1px #a8abae inset;
background:-webkit-linear-gradient(right,#e4e8ec,#e4e8ec 60%);
background:-moz-linear-gradient(right,#e4e8ec,#e4e8ec 60%);
background:linear-gradient(right,#e4e8ec,#e4e8ec 60%);
}
.black.rarrow:hover:after,
.black.larrow:hover:after{
background:-webkit-linear-gradient(top left,#818181,#575757);
background:-moz-linear-gradient(top left,#818181,#575757);
background:linear-gradient(top left,#818181,#575757);
}
.gray.rarrow:active:after,
.gray.larrow:active:after{
background:-webkit-linear-gradient(top left,#e4e8ec,#e4e8ec);
background:-moz-linear-gradient(top left,#e4e8ec,#e4e8ec);
background:linear-gradient(top left,#e4e8ec,#e4e8ec);
}
.gray.rarrow:active:after{
box-shadow: 0 1px 0 #b7babd inset,-1px 0 0 #b7babd inset;
}
.gray.larrow:active:after{
box-shadow: 0 -1px 0 #b7babd inset,1px 0 0 #b7babd inset;
}
html {
height: 100%;
}
body {
height: 100%;
font: 1.33em 'Roboto Condensed', arial;
color: #FFF;
text-align: center;
background-image: -webkit-radial-gradient(circle, #3c3b52 0%, #252233 80%);
background-image: radial-gradient(circle, #3c3b52 0%, #252233 80%);
}
h1 {
margin: .5em 0 0;
margin-bottom:20px;
padding: 0;
text-shadow: 0 4px rgba(0, 0, 0, 0.2);
}
* {
-moz-box-sizing: padding-box;
box-sizing: padding-box;
}
input[type=file]{
border-color:#fff;
/* border: none; */
outline:none;
cursor: pointer;
height:45px;
text-align: center;
}
.button{
/* width: 240px; */
line-height: 38px;
text-align: center;
font-weight: bold;
color: #fff;
text-shadow:1px 1px 1px #333;
border-radius: 5px;
margin:0 20px 20px 0;
position: relative;
overflow: hidden;
}
</style>
<script type="text/javascript">
function addline(){
newline = document.all.test.insertRow();
newline.insertCell().innerHTML="<input class='button gray side' type='file' name='file' size='60'>"+"<a onclick='javascript:removeline(this)'>移除</a>";
}
function removeline(obj){
var objSourceRow=obj.parentNode.parentNode;
var objTable=obj.parentNode.parentNode.parentNode.parentNode;
objTable.lastChild.removeChild(objSourceRow);
}
</script>
</head>
<body>
<form name="theform" method="post" action="${pageContext.request.contextPath }/FileUpLoadServlet1" enctype="multipart/form-data">
<h1 align="center">文件上传</h1>
<table id=test border="0" align="center">
<tr>
<td>
<input class="button gray side" type="file" name="file" size="60">
<a onclick="addline()"><font color="white">单击此处添加更多文件</font></a>
</td>
</tr>
</table>
<hr>
<input type="submit" style="width: 100;height: 40;font-size: 18px" />
</form>
</body>
</html>
第二个页面:ListFile.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%
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 'ListFile.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">
<style type="text/css">
a{
text-decoration: none;
color: rgba(255, 255, 255, 0.5);
}
.live {
overflow: hidden;
}
.live > li {
list-style: none;
position: relative;
padding: 0 0 0 2em;
margin: 0 0 .5em 10px;
-webkit-transition: .12s;
transition: .12s;
}
.live > li>a::before {
position: absolute;
content: '\2022';
font-family: Arial;
color: #FFF;
top: 0;
left: 0;
text-align: center;
font-size: 2em;
opacity: .5;
line-height: .75;
-webkit-transition: .5s;
transition: .5s;
}
.live > li>a:hover {
color: #FFF;
}
.live > li>a:hover::before {
-webkit-transform: scale(2);
-ms-transform: scale(2);
transform: scale(2);
opacity: 1;
text-shadow: 0 0 4px;
-webkit-transition: .1s;
transition: .1s;
}
.live.type2 > li>a::before {
content: '';
width: 10px;
height: 10px;
background: #FFF;
border-radius: 3px;
line-height: 0;
top: .27em;
left: 5px;
}
.live.type2 > li>a:hover::before {
-webkit-transform: none;
-ms-transform: none;
transform: none;
border-radius: 5px;
width: 25px;
left: -10px;
background: #BA5353;
}
html {
height: 100%;
}
body {
height: 100%;
font: 1.33em 'Roboto Condensed', arial;
color: #FFF;
text-align: center;
background-image: -webkit-radial-gradient(circle, #3c3b52 0%, #252233 80%);
background-image: radial-gradient(circle, #3c3b52 0%, #252233 80%);
}
h1 {
margin: .5em 0 0;
padding: 0;
text-shadow: 0 4px rgba(0, 0, 0, 0.2);
}
* {
-moz-box-sizing: padding-box;
box-sizing: padding-box;
}
ul {
width: 28%;
display: inline-block;
text-align: left;
vertical-align: top;
background: rgba(0, 0, 0, 0.2);
color: rgba(255, 255, 255, 0.5);
border-radius: 5px;
padding: 1.5em;
margin: 2%;
box-shadow: 0 0 8px rgba(0, 0, 0, 0.2);
}
</style>
</head>
<body>
<h1>下载列表</h1><br>
<ul class="live type2">
<c:if test="${not empty list }">
<c:forEach items="${list }" var="fileName">
<li><a href="${pageContext.request.contextPath }/DownServlet?fileName=${fileName}">${fn:substringAfter(fileName,"~~")}</a></li>
</c:forEach>
</c:if>
</ul>
</body>
</html>
filter包下面的字符过滤器:EncodingFilter
package filter;
import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class EncodingFilter implements Filter{
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
//代理模式
//转型
final HttpServletRequest request=(HttpServletRequest)req;
HttpServletResponse response=(HttpServletResponse)resp;
//处理公共业务
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//对指定接口的某个方法进行功能扩展,使用代理,即对request对象创建代理对象
/*
* public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h)
*/
HttpServletRequest proxy=(HttpServletRequest)Proxy.newProxyInstance(
request.getClass().getClassLoader(),//指定类加载器
new Class[]{HttpServletRequest.class},//接口类型
new InvocationHandler() {//事件处理器
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
//定义方法的返回值
Object returnValue=null;
String methodName=method.getName();
//判断:get方法
if("getParameter".equals(methodName)){
//调用目标对象的方法
String value=request.getParameter(args[0].toString());
String methodSubmit=request.getMethod();
if("get".equals(methodSubmit)){
if(value!=null && !"".equals(value.trim())){
//处理中文乱码
value=new String(value.getBytes("ISO8859-1"),"utf-8");
}
}
return value;
}else{
//执行request对象的其他方法
returnValue=method.invoke(request, args);
}
return returnValue;
}
});
//放行
chain.doFilter(proxy, response);
}
public void init(FilterConfig arg0) throws ServletException {
}
}
在 web.xml配置
<filter>
<filter-name>EncodingFilter</filter-name>
<filter-class>filter.EncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>EncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
上传的servlet:FileUpLoadServlet1
package upload;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.UUID;
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.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class FileUpLoadServlet1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
FileItemFactory factory=new DiskFileItemFactory();
ServletFileUpload upload=new ServletFileUpload();
upload.setFileItemFactory(factory);
upload.setFileSizeMax(1024*1024*30);//单个文件不超过30m
upload.setSizeMax(1024*1024*100);//总文件不超过100m
upload.setHeaderEncoding("utf-8");//设置编码,防止乱码
if(upload.isMultipartContent(request)){
try {
List<FileItem> list=upload.parseRequest(request);
for (FileItem fileItem : list) {
if(!fileItem.isFormField()){
String name=fileItem.getName();
if(name!=null && !"".equals(name)){
String uuid=UUID.randomUUID().toString();
String path=getServletContext().getRealPath("/upload");
name=uuid+"~~"+name;
File file=new File(path,name);
fileItem.write(file);
response.getWriter().write("单个文件上传成功!");
}
}
}
response.getWriter().write("多个文件上传成功!");
} catch (Exception e) {
e.printStackTrace();
}
}else{
response.getWriter().write("不处理!");
}
response.sendRedirect(request.getContextPath()+"/ListFileServlet");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
显示下载列表的servlet:ListFileServlet
package upload;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ListFileServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
List<String> list=new ArrayList<String>();
String path=getServletContext().getRealPath("/upload");
File file=new File(path);
if(file.isDirectory()){
File[] files=file.listFiles();
for (File file2 : files) {
String fileName=file2.getName();
list.add(fileName);
}
}
request.setAttribute("list", list);
request.getRequestDispatcher("/ListFile.jsp").forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
下载的servlet:DownServlet
package upload;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
public class DownServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String fileName=request.getParameter("fileName");
String path=getServletContext().getRealPath("/upload");
File file=new File(path,fileName);
if(!file.exists()){
response.getWriter().print("该文件不存在!");
return;
}
response.addHeader("content-disposition", "attachment;filename="+fileName);
IOUtils.copy(new FileInputStream(file), response.getOutputStream());
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
所有代码已上传,上传后的文件会放在tomcat服务器里面,所以在自己的项目下是找不到文件的,必须去tomcat的webapps目录下,找到自己的项目名,然后再找到upload,就可以看见上传的文件了。
项目所需jar包地址:https://download.csdn.net/download/rosachampagne/10717258