Home > Java > javaTutorial > body text

JSP implements file download

巴扎黑
Release: 2016-12-20 14:04:28
Original
1216 people have browsed it

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>
Copy after login

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();
}
}
%>
Copy after login


Related labels:
jsp
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!