其他分享
首页 > 其他分享> > ServletContext_功能_获取文件服务器路径和文件下载_代码实现

ServletContext_功能_获取文件服务器路径和文件下载_代码实现

作者:互联网

ServletContext对象范围:所有用户所有请求的数据

  获取文件的真实服务器路径

方法:String getRealpath(String path)

  

@WebServlet("/ServletContextDemo4")
public class ServletContextDemo4 extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext servletContext1 = this.getServletContext();
        String realPath = servletContext1.getRealPath("/b.txt");
        System.out.println(realPath);

        String realPath1 = servletContext1.getRealPath("/WEB-INF");
        System.out.println(realPath1);

        String a = servletContext1.getRealPath("WEB-INF/classes/a.txt");
        System.out.println(a);

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }


}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

文件下载_代码实现

案例:

  文件下载显示超链接

  点击超链接后弹出下载提示框

   文件图片文件下载

分析:

     超链接指向的资源如果能够被浏览器解析,则浏览器中展示,如果不能解析,则弹出下载提示框。不满足需求。

  任何资源都必须弹出下载提示框

  使用响应设置资源的打开方式

步骤

  定义页面,编辑超链接href属性,指向Servlet,传递资源名称filename

  定义Servlet

    获取文件名称

    使用字节输出流加载文件进内存

    制定Response的响应:Content-dispostion:attacgment;filename=xxx

    将数据写出到Response输出流

 

 

@WebServlet("/downloadloadServlet")
public class ServletContextDemo5 extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String filename = req.getParameter("filename");

        ServletContext servletContext = this.getServletContext();
        String realPath = servletContext.getRealPath("/ass/" + filename);
        FileInputStream fileInputStream = new FileInputStream(realPath);


        String mimeType = servletContext.getMimeType(filename);
        resp.setHeader("content-type",mimeType);
        resp.setHeader("content-disposition","attachment;filename="+filename);


        ServletOutputStream outputStream = resp.getOutputStream();
        byte[] bytes = new byte[1024];

        int len = 0;
        while ((len = fileInputStream.read(bytes))!= -1){
            outputStream.write(bytes,0,len);
        }

        fileInputStream.close();
        outputStream.close();

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

 

 

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <a href="/ass/banner_2.jpg">图片</a>
    <a href="/ass/bna.mp4">视频</a>

    <a href="/downloadloadServlet?filename=banner_2.jpg">图片1</a>

    <a href="/downloadloadServlet?filename=bna.mp4">视频1</a>
</body>
</html>

搜索

复制

标签:文件,String,resp,req,filename,ServletContext,服务器,下载
来源: https://www.cnblogs.com/12-12-12/p/16575272.html