1.首先在web-inf下创建文件夹,向其中加入所要下载的东西,本文以pdf格式的java编程思想为例
2. 在index.jsp中创建一个简单的a标签,指向DownLoadServlets
3. 创建对应的Servlet,并在dopost()方法中写如下代码
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
String name = "Java编程思想(第4版).pdf";
FileInputStream fis = null;
BufferedInputStream bis = null;
OutputStream os = null;
try {
//获取下载文件所在路径
String path = request.getServletContext().getRealPath("/WEB-INF/data/"+name);
//文件
File file = new File(path);
//判断文件是否存在
if(file.exists()){
//且仅当此对象抽象路径名表示的文件或目录存在时,返回true
response.setContentType("application/pdf");
//控制下载文件的名字
response.addHeader("Content-Disposition", "attachment;filename="+name);
byte buf[] = new byte[1024];
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
os = response.getOutputStream();
int i = bis.read(buf);
while(i!=-1){
os.write(buf,0,i);
i = bis.read(buf);
}
}else{
System.out.println("您下载的资源已经不存在了");
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
os.close();
bis.close();
fis.close();
}
}