日期:2014-05-16 浏览次数:20342 次
一、实现功能:页面上显示附件链接,点击链接,弹出“文件下载”框,打开或保存文件。
(ps:最简单常见的功能,却有很多地方需要注意)
二、过程:采用 servlet1 提供“附件列表”数据,在页面显示所有附件链接,点击链接经过servlet2处理,弹出“文件下载”框,打开或保存文件。
1、在index页面,通过点击链接向GotoAttachServlet发出请求。
2、GotoAttachServlet 提供附件列表,转向download.jsp 页面。
3、在download.jsp 点击某个附件链接,通过DownloadServlet处理,弹出“文件下载”框,打开或保存该文件。
?
注:为了方便,数据没有从数据库中取。整个过程是完整的,其实只要关注DownloadServlet.java中相关代码即可。
?
三、实现。
1、index中的相关代码。
<a href="GotoAttachServlet">附件页面</a>
?2、GotoAttachServlet中相关代码。
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<Attachment>attachList = new ArrayList<Attachment>(); Attachment attach1=new Attachment(1,"flower.png","d://flower.jpg"); attachList.add(attach1); Attachment attach2=new Attachment(2,"tree.txt","d://tree.txt"); attachList.add(attach2); request.setAttribute("attachList", attachList); request.getRequestDispatcher("download.jsp").forward(request, response); }
?3、download.jsp 代码。
??4、DownLoadServlet.java中相关代码。 ?<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<!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>
<script src="<%=basePath%>js/jquery-1.4.4.js"></script>
<script type="text/javascript">
function download(attachId){
var url="/MyWeb/DownloadServlet?attachId="+attachId;
$('#attachmentForm').attr('action',url).submit();
}
</script>
</head>
<body>
<div>附件下载</div>
<form id="attachmentForm" method="post">
<table>
<tr>
<td>附件:</td>
<td>
<ul>
<c:forEach items="${attachList}" var="attach">
<li>
<a href="#" onclick="download('${attach.id}')">${attach.name}</a>
</li>
</c:forEach>
</ul>
</td>
</tr>
</table>
</form>
</body>
</html>
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String idStr=request.getParameter("attachId");
Attachment attachment=null;
if(idStr.equals("1")){
attachment=new Attachment(1,"flower.png","d://flower.jpg");
}else{
attachment=new Attachment(2,"tree.txt","d://tree.txt");
}
String downFilePath=attachment.getPath();
String fileName = attachment.getName();
fileName = URLEncoder.encode(fileName, "UTF-8");
// 设置响应信息