JSP实现文件下载代码
<%
String path=request.getContextPath();
%>
<title>login.jsp</title>
<body>
<a href="<%=path %>/Download.jsp">download</a>
</body>
<title>Download.jsp</title>
<body>
<%
response.setContentType("application/x-download");
String filedownload="f:/稿子.ppt";
String filedisplay = "演示文稿.ppt";
String filenamedisplay = URLEncoder.encode(filedisplay,"UTF-8");
response.addHeader("Content-Disposition","attachment;filename=" + filenamedisplay);
OutputStream outp = null;
FileInputStream in = null;
try
{
outp = response.getOutputStream();
in = new FileInputStream(filedownload);
byte[] b = new byte[1024];
int i = 0;
while((i = in.read(b)) > 0)
{
outp.write(b, 0, i);
}
outp.flush();
}
catch(Exception e)
{
System.out.println("Error!");
e.printStackTrace();
}
finally
{
if(in != null)
{
in.close();
in = null;
}
if(outp != null)
{
outp.close();
outp = null;
}
}
%>
</body>
<%
String path=request.getContextPath();
%>
<title>login.jsp</title>
<body>
<a href="<%=path %>/Download.jsp">download</a>
</body>
<title>Download.jsp</title>
<body>
<%
response.setContentType("application/x-download");
String filedownload="f:/稿子.ppt";
String filedisplay = "演示文稿.ppt";
String filenamedisplay = URLEncoder.encode(filedisplay,"UTF-8");
response.addHeader("Content-Disposition","attachment;filename=" + filenamedisplay);
OutputStream outp = null;
FileInputStream in = null;
try
{
outp = response.getOutputStream();
in = new FileInputStream(filedownload);
byte[] b = new byte[1024];
int i = 0;
while((i = in.read(b)) > 0)
{
outp.write(b, 0, i);
}
outp.flush();
}
catch(Exception e)
{
System.out.println("Error!");
e.printStackTrace();
}
finally
{
if(in != null)
{
in.close();
in = null;
}
if(outp != null)
{
outp.close();
outp = null;
}
}
%>
</body>
本文介绍了一种使用JSP技术实现文件下载的方法。通过设置HTTP响应头并利用Servlet读取文件内容来完成文件的下载过程。该示例代码展示了如何指定下载文件名及路径,并通过流操作将文件发送给客户端。

6174

被折叠的 条评论
为什么被折叠?



