下面按照从用户访问请求开始,到得到结果的处理流程(从用户上传界面到用户下载处理的整个过程代码).粘贴的代码
1.视图界面upload.jsp代码
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@include file="/common/tag.jsp"%>
<%@include file="/common/jquery.jsp"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<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">
-->
<script type="text/javascript">
function checkUpload(){
var $upFile = $("#upfile");
if($upFile.val()==""){
return false;
}
return true;
}
</script>
</head>
<body>
<form action="${pageContext.request.contextPath}/uploadFile.do"
method="post" enctype="multipart/form-data" οnsubmit="return checkUpload()">
<table>
<tr>
<td colspan="2">${requestScope.msg}</td>
</tr>
<tr>
<td><fmt:message key="uploadUser" /></td>
<td><input type="text" name="user" /></td>
</tr>
<tr>
<td><fmt:message key="uploadfile" /></td>
<td><input type="file" name="upload" id="upfile" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit"
value='<fmt:message key="submitUpload"></fmt:message>' /></td>
</tr>
</table>
</form>
</body>
</html>
2.视图upload中使用的tag.jsp和jquery.jsp代码如下
tag.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"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<fmt:setBundle basename="csdn"/>
jquery.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 'jquery.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">
<!-- 引入jquery easyui的css样式 -->
<link rel="stylesheet" type="text/css"
href="${pageContext.request.contextPath}/themes/default/easyui.css">
<link rel="stylesheet" type="text/css"
href="${pageContext.request.contextPath}/themes/icon.css">
<!-- 引入jQuery easyui的js文件 并且引入了jquery.js文件 -->
<script type="text/javascript"
src="${pageContext.request.contextPath}/js/jquery.min.js"></script>
<script type="text/javascript"
src="${pageContext.request.contextPath}/js/jquery.easyui.min.js"></script>
</head>
<body>
</body>
</html>
依赖的国际化资源文件内容:csdn_zh.properties
uploadUser=\u4E0A\u4F20\u8005
submitUpload=\u4E0A\u4F20
uploadfile=\u4E0A\u4F20\u6587\u4EF6
3.上传文件 -servlet处理类
package upload.servlet;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
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.FileUploadException;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
*
* @author chenhongjun
*
*/
public class UploadServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 判断是否是上传表单是否为multipart/form-data类型
if (ServletFileUpload.isMultipartContent(request)) {
// 创建 DiskFileItemFactory工厂 对象
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
// 创建DiskFileItemFactory的解析器对象
ServletFileUpload fileUpload = new ServletFileUpload(
diskFileItemFactory);
// 设置上传头的编码格式
fileUpload.setHeaderEncoding("UTF-8");
// 设置文件上传大小的限制 为1M
fileUpload.setFileSizeMax(1024 * 1024);
// 注册监听 已经上传的进度
fileUpload.setProgressListener(new ProgressListener() {
@Override
public void update(long pBytesRead, long pContentLength,
int pItems) {
System.out.println("到现在为止, " + pBytesRead + " 字节已上传,总大小为 "
+ pContentLength);
}
});
try {
// 解析request请求
List<FileItem> fileItems = fileUpload.parseRequest(request);
// fileItem 对应<input type="file" name="upload" id="upfile" />
// fileItem <input type="text" name="user" />
// 遍历操作
for (FileItem fileItem : fileItems) {
// 首先判断 是否是 普通的文本
if (fileItem.isFormField()) {
// 获取字段name值
String name = fileItem.getFieldName();
// 字段name值 相对应的value
String value = fileItem.getString();
} else {
// 获取上传文件的名称 文件名称可能是(c:\xxxx\xxx\xx.jpg(IE浏览器) 或者
// xx.jpg(火狐浏览器));
String fileName = fileItem.getName();
// 如果在IE浏览器中 ---> 先解析出xx.jpg
int index = fileName.lastIndexOf("\\");
// 进行判断是否 含有\
if (index != -1) {
// 含有\ 就解析出xx.jpg
fileName = fileName.substring(index + 1);
}
// 添加时间戳 保证上传的文件名称唯一
fileName = System.currentTimeMillis() + "_" + fileName;
// 设置保存的路径 防止外部直接访问 存放在WEB-INF目录下
String path = request.getServletContext().getRealPath(
"/WEB-INF/upload");
// 创建保存的文件
File file = new File(path, fileName);
// 获取请求的输入流对象
InputStream is = fileItem.getInputStream();
// 输出流对象
FileOutputStream fos = new FileOutputStream(file);
// 缓冲区大小
byte[] buffer = new byte[1024];
// 读取的长度
int len = 0;
// 读取 如果读取的结果为-1 证明读取完毕,否则继续读取
while ((len = is.read(buffer)) != -1) {
// 写入文件
fos.write(buffer, 0, len);
}
// 关闭流的操作
fos.close();
is.close();
// 删除临时文件
fileItem.delete();
}
}
// 转发到 显示所有上传文件的servlet处理
request.getRequestDispatcher("/listFile.do").forward(request,
response);
} catch (FileUploadException e) {
// 获取错误的异常信息
String message = e.getMessage();
// The field upload exceeds its maximum permitted size of
// 1048576 bytes.
// 如果存在 限制文件大小的字符 就提示 文件上传过大
if (message.contains("permitted size of")) {
request.setAttribute("msg", "文件上传过大");
}
// 转发到 文件上传界面
request.getRequestDispatcher("./upload.jsp").forward(request,
response);
}
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
4.显示有上传文件的servlet处理类
package down.servlet;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author chenhongjun
*
*/
public class ListFileServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 遍历WEB-INF/upload下面的所有文件 并保存到map集合中
// 获取下载的路径
String path = request.getServletContext().getRealPath("/WEB-INF/upload");
// 获取下载路径的文件对象
File file = new File(path);
//声明用来存储上传文件的 map对象
Map<String,String> map = new HashMap<String,String>();
//通过遍历 把文件存储到map中
listFiles(file, map);
//存储到request域中
request.setAttribute("map", map);
//转发到显示的界面
request.getRequestDispatcher("./listfile.jsp").forward(request,
response);
}
//遍历文件操作
private void listFiles(File file, Map<String, String> map) {
//获取当前文件下面的所有文件
File files[] = file.listFiles();
//遍历
for (File f : files) {
//判断是否是 文件
if (f.isFile()) {
//获取文件名称
String fileName = f.getName();
//获取_字符所在的索引位置
int index = fileName.indexOf("_");
//判断是否存在
if (index != -1) {
//存在 就把文件存储到map中
map.put(fileName, fileName.substring(index + 1));
} else {
//如果不存在,就暂时不处理
}
} else {
//如果是文件夹,再进行遍历
listFiles(f, map);
}
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
5.显示所有上传文件 listfile.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@include file="/common/tag.jsp"%>
<%@include file="/common/jquery.jsp"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<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>
<!-- 下载方式 以流的方式进行处理 -->
<!-- 遍历map集合 -->
<c:forEach var="m" items="${requestScope.map}">
<!-- 定义下载的url地址 及下载传递的文件名称 -->
<c:url var="downurl" value="./downfile.do">
<c:param name="fileName">${m.key}</c:param>
</c:url>
<!-- 创建下载的连接 -->
<a href="${downurl}">${m.value}</a><br/>
</c:forEach>
<!-- 传统的方式下载 -->
<a href="${pageContext.request.contextPath}/js/jquery.min.js">下载我</a>
</body>
</html>
package down.servlet;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DownFileServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 文件下载
// 获取下载的文件名称
String fileName = request.getParameter("fileName");
// 找到下载文件的具体路径
String filePath = request.getServletContext().getRealPath(
"/WEB-INF/upload/" + fileName);
// 根据路径创建文件
File file = new File(filePath);
// 创建输入流对象
FileInputStream fis = new FileInputStream(file);
// 设置下载的类型 告诉浏览器 需要以下载的方式操作
response.setContentType("application/x-msdownload");
// 下载头设置
response.setHeader("content-disposition", "attachment;fileName="
+ java.net.URLEncoder.encode(fileName, "UTF-8"));
// 写出的流
OutputStream os = response.getOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fis.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
os.close();
fis.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}