
把如下代码如下写在jsp页面文件:
<%@page import="java.io.*" %>
<%@page import="java.util.*" %>
<%
response.setContentType("application/pdf")
response.setHeader("Content-Disposition","attachmentfilename=输出文件.pdf")
ByteArrayOutputStream baos= (ByteArrayOutputStream)request.getAttribute("pdfOutputStream")
OutputStream output = new DataOutputStream( response.getOutputStream() )
baos.writeTo(output)
output.close()
out.clear()
%>
首先你要明确一个概念,数据库中是不可能存这些文件的,存的最多是这些文件对应的地址,是String类型的数据。在这基础上来看这些代码。注意标注的1234:
//获取网站部署路径(通过ServletContext对象),用于确定下载文件位置,从而实现下载
String path = servletContext.getRealPath("/")
//1.设置文件ContentType类型,这样设置,会自动判断下载文件类型
response.setContentType("multipart/form-data")
//2.设置文件头:最后一个参数是设置下载文件名(假如我们叫a.pdf)
response.setHeader("Content-Disposition", "attachmentfileName="+"a.pdf")
ServletOutputStream out
//通过文件路径获得File对象(假如此路径中有一个download.pdf文件)
File file = new File(path + "download/" + "download.pdf")
try {
FileInputStream inputStream = new FileInputStream(file)
//3.通过response获取ServletOutputStream对象(out)
out = response.getOutputStream()
int b = 0
byte[] buffer = new byte[512]
while (b != -1){
b = inputStream.read(buffer)
//4.写到输出流(out)中
out.write(buffer,0,b)
}
inputStream.close()
out.close()
out.flush()
} catch (IOException e) {
e.printStackTrace()
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)