欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  Java

JSP实现文件下载

程序员文章站 2022-03-19 19:51:54
...
showLink.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>download file</title>
</head> 
<body>
<a href="download.jsp">click here</a>
</body>
</html>

download.jsp

<%@ page language="java"
contentType="application/x-msdownload; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.io.*"%>
<%@ page import="java.net.*"%>
<%
response.reset();
response.setContentType("application/x-download");
String realPath = application.getRealPath("download");
String fileName = "bbb.txt";
fileName = URLEncoder.encode(fileName, "UTF-8");
response.addHeader("Content-Disposition", "attachment;filename="
+ fileName);
FileInputStream fis = null;
OutputStream os = null;
try {
fis = new FileInputStream(realPath + "/" + fileName);
os = response.getOutputStream();
byte[] bbuf = new byte[1024];
int hasRead = 0;
while ((hasRead = fis.read(bbuf)) > 0) {
os.write(bbuf, 0, hasRead);
}
os.flush();
out.clear();
out = pageContext.pushBody();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fis != null) {
fis.close();
}
}
%>