>  기사  >  Java  >  JSP는 파일 다운로드를 구현합니다.

JSP는 파일 다운로드를 구현합니다.

巴扎黑
巴扎黑원래의
2016-12-20 14:04:281211검색

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


성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.