蛋疼
没有servlet,只能把jsp当成是servlet来用,
这里面我用了两个jsp页面,都是最简单的功能,没有样式
下载链接jsp
代码:
js:
//下载
function xiazai(){
window.location.href = "download.jsp";
}
html:
<span style="cursor:pointer" οnclick="xiazai()">aa.png</span>
做servlet用的jsp
<body>
<%
//关于文件下载时采用文件流输出的方式处理:
//加上response.reset(),并且所有的%>后面不要换行,包括最后一个;
response.reset();//可以加也可以不加
response.setContentType("application/x-download");
String filedownload = request.getRealPath("/")+"/pic/aa.png"; //我这边写死的路径,之前已经把图片传到tomcat里面了,这里面的路径可以从表里读
String filedisplay = "test.png";
//String filedisplay = URLEncoder.encode(filedisplay,"UTF-8");
response.addHeader("Content-Disposition","attachment;filename=" + filedisplay);
java.io.OutputStream outp = null;
java.io.FileInputStream in = null;
try
{
outp = response.getOutputStream();
in = new java.io.FileInputStream(filedownload);
byte[] b = new byte[1024];
int i = 0;
while((i = in.read(b)) > 0)
{
outp.write(b, 0, i);
}
//
outp.flush();
//要加以下两句话,否则会报错
//java.lang.IllegalStateException: getOutputStream() has already been called for this respons
out.clear();
out = pageContext.pushBody();
}
catch(Exception e)
{
System.out.println("Error!");
e.printStackTrace();
}
finally
{
if(in != null)
{
in.close();
in = null;
}
}
%>
</body>
这段代码,可能比较乱对不起大家了,主要是为了记载下供自己后面去学习的