用于下载文件的Servlet_陈焜浩Arain_新浪博客

有时只是用于开发一些小功能的话,未必需要集成很多框架,简单的功能反而使用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这个文件的下载了~
  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值