servlet下载文件实现代码详解(五)
本文实例为大家分享了servlet下载文件的具体代码,供大家参考,具体内容如下
1.servlet下载文件
servlet下载文件就是将服务器端的文件传输到客户端。
2案例
下载文件servlet类
packagecom.learn;
importjavax.servlet.ServletConfig;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importjava.io.File;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.OutputStream;
/**
*CreatedbyAdministratoron2017/09/24.
*/
publicclassDownLoadServletextendsHttpServlet{
privateStringfilePath;
@Override
publicvoidinit(ServletConfigconfig)throwsServletException{
super.init(config);
filePath=config.getInitParameter("filePath");
//初始化路径
//filePath=config.getServletContext().getRealPath(filePath);
System.out.println("初始化文件路径:"+filePath);
}
@Override
protectedvoiddoGet(HttpServletRequestreq,HttpServletResponseresp)throwsServletException,IOException{
doPost(req,resp);
}
@Override
protectedvoiddoPost(HttpServletRequestreq,HttpServletResponseresp)throwsServletException,IOException{
OutputStreamout;//输出流
InputStreamin;//输入流
StringfileName=req.getParameter("fileName");
System.out.println("文件名称:"+fileName);
//如果把文件名为null则提示用户
if(fileName==null){
out=resp.getOutputStream();
out.write("pleaseinputfileName".getBytes());
out.close();
}
//获取文件流
in=getServletContext().getResourceAsStream(filePath+File.separator+fileName);
System.out.println(in==null?true:false);
intlength=in.available();
//设置返回消息头部信息
resp.setContentType("application/force-download");
resp.setHeader("Content-Length",String.valueOf(length));
resp.setHeader("content-disposition","attachment;filename=\""+fileName+"\"");
//输出文件到客户端
out=resp.getOutputStream();
intbytesend=0;
byte[]buff=newbyte[512];
while((bytesend=in.read(buff))!=-1){
out.write(buff,0,bytesend);
}
in.close();
out.close();
}
}
web.xml配置
download com.learn.DownLoadServlet filePath file download /download
热门推荐
10 香港老妈结婚祝福语简短
11 毕业立体贺卡祝福语简短
12 简短新年年会祝福语
13 评论小品祝福语大全简短
14 恭喜师兄结婚祝福语简短
15 员工集体辞职祝福语简短
16 高中新生祝福语 简短
17 装修祝福语男生搞笑简短
18 生日开业蛋糕祝福语简短