<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 トランス..."/> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 トランス...">

ホームページ  >  記事  >  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 までご連絡ください。