开发步骤:
前提:指定表单上传类型是文件上传表单 enctype="multipart/form-data"
提交方式是post
表单中存在文本域对象
通过FileUpload组件解析内容组件使用的步骤下载组件,
引入jar文件配置文件properties/xml学习API
需要的jar包:commons-fileupload-1.2.1.jar commons-io-1.4.jar jstl.jar standard.jar
共有三个页面:
用户页面:index.jsp(首页) upload.jsp(文件上传页面) downlist.jsp(文件下载页面)
---------------------------------用户页面:index.jsp(首页)-------------------------
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>首页</title>
</head>
<body>
<a href="${pageContext.request.contextPath }/upload.jsp">文件上传</a>
<a href="${pageContext.request.contextPath }/Upload2?method=downList">文件下载</a>
</body>
</html>
---------------------------------upload.jsp(文件上传页面)-------------------------
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>文件上传</title>
</head>
<body>
<form method="post" action="${pageContext.request.contextPath }/Upload2?method=upload" enctype="multipart/form-data">
用户名:<input name="username" type="text"><br>
文件:<input type="file" name="file_img"><br>
<input type="submit" value="上传">
</form>
</body>
</html>
---------------------------------downlist.jsp(文件下载页面)-------------------------
<%@ page language="java" import="java.util.*"
contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%-- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> --%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>下载页面</title>
</head>
<body>
<table border="1" align="center">
<tr>
<th>序号</th>
<th>文件名</th>
<th>操作</th>
</tr>
<c:forEach var="en" items="${requestScope.filenames}" varStatus="vs">
<tr>
<%-- <td>${request.filenames }</td>
<td><%=request.getAttribute("filenames") %></td> --%>
<td>${vs.count }</td>
<td>${en.value }</td>
<td>
<%--<a href="${pageContext.request.contextPath }/fileServlet?method=down&..">下载</a>--%>
<!-- 构建一个地址 -->
<c:url var="url" value="Upload2">
<c:param name="method" value="down"></c:param>
<c:param name="fileName" value="${en.key }"></c:param>
</c:url>
<!-- 使用上面地址 -->
<a href="${url }">下载</a>
</td>
</tr>
</c:forEach>
</table>
</body>
</html>
-------------------------------------------------------------------------------------------------------后台代码:Upload2.jsp-------------------------------------------------------------------------
public class Upload2 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
//获取请求参数,区分不同的操作类型
String method = req.getParameter("method");
if("upload".equals(method)){
//上传
upload(req,resp);
}
else if("downList".equals(method)){
//进入下载页面
downList(req,resp);
}
else if("down".equals(method)){
//下载
down(req,resp);
}
}
//3.处理下载
private void down(HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException, IOException {
// TODO Auto-generated method stub
//获取用户下载的文件名称(url地址后追加数据,get)
String fileName= req.getParameter("fileName");
//转成UTF-8编码
fileName=new String(fileName.getBytes("ISO8859-1"),"UTF-8");
//先获取上传目录路径
String basePath = getServletContext().getRealPath("/upload");
//获取一个文件输入流
InputStream is = new FileInputStream(new File(basePath,fileName));
//如果文件名是中文,需要进行url编码
fileName = URLEncoder.encode(fileName,"UTF-8");
//设置下载的响应头
resp.setHeader("content-disposition", "attachment;fileName="+fileName);
//获取response字节流
OutputStream out = resp.getOutputStream();
byte[] b= new byte[1024];
int len =-1;
while((len=is.read(b))!=-1){
out.write(b,0,len);
}
//关闭流
out.close();
is.close();
}
//进入文件下载列表
private void downList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
//实现思路:先获取upload目录下所有文件的文件名,再保存,跳转到down.jsp列表展示
//1.初始化map集合,及所有的文件的文件名
Map<String,String> fileNames = new HashMap<>();
//2.获取上传目录,及其下的所有文件名
String basePath = getServletContext().getRealPath("/upload");
//目录
File file = new File(basePath);
//目录下,所有的文件名
String[] list = file.list();
//遍历,封装
if(list!=null&&list.length>0){
for(int i=0;i<list.length;i++){
//全名
String filename = list[i];
//短名
String shortName = filename.substring(filename.indexOf("#")+1);
//封装
fileNames.put(filename, shortName);
}
}
//3.保存到request域中
req.setAttribute("filenames", fileNames);
//4.转发
req.getRequestDispatcher("/downlist.jsp").forward(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(req, resp);
}
//处理文件上传
private void upload(HttpServletRequest req, HttpServletResponse resp) {
// TODO Auto-generated method stub
// 保存在服务器上项目下的upload目录下
try {
// 1.文件上传工厂
DiskFileItemFactory factory = new DiskFileItemFactory();
// 2.创建文件上传核心类
ServletFileUpload upload = new ServletFileUpload(factory);
// 一.设置单个文件允许的最大的大小 30M
upload.setFileSizeMax(30 * 10234 * 1024);
// 二.设置文件上传表单的允许的总大小 80M
upload.setSizeMax(80 * 1024 * 1024);
// 三.设置上传表单文件名的编码
upload.setHeaderEncoding("UTF-8");
// 3.判断,单前表单是否为文件上传表单
if (upload.isMultipartContent(req)) {
// 4.把请求数据转换为一个FileItem对象,再用集合封装
List<FileItem> list = upload.parseRequest(req);
for (FileItem item : list) {
// 判读:普通文本数据
if (item.isFormField()) {
// 普通数据
String fieldName = item.getFieldName(); // 表单元素名称
String content = item.getString(); // 表单元素名称,对应的数据
// item.getString("UTF-8");指定编码
System.out.println(fieldName + ":" + content);
} else {
/************* 文件上传 ***********/
// a.获取文件名称
String name = item.getName();
// --处理上传文件重名问题
// a1.先得到唯一标识
String id = UUID.randomUUID().toString();
// a2.拼接文件名
name = id + "#" + name;
// b.得到目标上传目录
String basePath = getServletContext().getRealPath("/upload");
System.out.println(basePath);
// c.创建要上传的文件对象
File file = new File(basePath, name);
// d.上传
item.write(file);
// item.delete();//删除组件运行时产生的临时文件
System.out.println("上传成功");
}
}
} else {
System.out.println("不做处理");
}
} catch (Exception e) {
}
}
}