有时只是用于开发一些小功能的话,未必需要集成很多框架,简单的功能反而使用Servlet比较简单。
下面是一个用于下载文件的Servlet,使用继承HttpServlet类的方式来实现:
public class FileDownloadServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//获取文件下载路径
String path = getServletContext().getRealPath("/") + "images/";
//文件名,也可以从HttpServletRequest 中获取
String filename = "1.jpg";
File file = new File(path + filename);
if(file.exists()){
//设置相应类型application/octet-stream
resp.setContentType("application/x-msdownload");
//设置头信息 Content-Disposition为属性名 附件形式打开下载文件 指定名称 为 设定的filename
resp.setHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
//输入流写入输出流
InputStream inputStream = new FileInputStream(file);
ServletOutputStream ouputStream = resp.getOutputStream();
byte b[] = new byte[1024];
int n ;
//循环读取 !=-1读取完毕
while((n = inputStream.read(b)) != -1){
//写入到输出流 从0读取到n
ouputStream.write(b,0,n);
}
//关闭流、释放资源
ouputStream.close();
inputStream.close();
}else{
req.setAttribute("errorResult", "文件不存在下载失败!");
RequestDispatcher dispatcher = req.getRequestDispatcher("jsp/01.jsp");
dispatcher.forward(req, resp);
}
}
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req,resp);
}
}
然后在web.xml中声名该Servlet:
DownloadServlet
utils.FileDownloadServlet
DownloadServlet
/downloadServlet.do
通过/downloadServlet.do即可完成对1.jpg这个文件的下载了~