zoukankan      html  css  js  c++  java
  • HttpServletResponse

    什么是HttpSevletResponse

    web服务器接收到客户端的http请求,针对这个请求,分别创建一个代表请求的HttpServletRequest对象,代表响应的一个HttpServletResponse

    案例:下载文件

    下载文件思路:

    • 下载文件路径
    • 下载文件名称
    • 浏览器支持下载格式
    • 获取下载文件的输入流
    • 创建缓冲区
    • 获取OutputStream对象
    • 将FileOutStream流写入到buffer缓冲区
    • OutputStream将缓冲区数据输出到客户端
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 下载文件路径
        String realPath = "xxxx";
        System.out.println("下载文件的路径:"+realPath);
        // 2. 下载文件名称
        String fileName = realPath.substring(realPath.lastIndexOf("\") + 1);
        // 3. 浏览器支持下载格式
        resp.setHeader("Content-Disposition","attachment;filename="+URLEncoder.encode(fileName,"UTF-8"));
        // 4. 获取下载文件的输入流
        FileInputStream in = new FileInputStream(realPath);
        // 5. 创建缓冲区
        int len = 0;
        byte[] buffer = new byte[1024];
        // 6. 获取OutputStream对象
        ServletOutputStream out = resp.getOutputStream();
        // 7. 将FileOutputStream流写入到buffer缓冲区,使用OutputStream将缓冲区中的数据输出到客户端!
        while ((len=in.read(buffer))>0){
            out.write(buffer,0,len);
        }
    
        in.close();
        out.close();
    }
    
  • 相关阅读:
    C#创建Windows Service(Windows 服务)基础教程
    c#写windows服务
    怎么样快速学习AngularJS?
    Web API 安全问题
    ASP.NET Web API身份验证和授权
    通过HttpClient来调用Web Api接口~续~实体参数的传递
    在WebApi中实现Cors访问
    SQL Server 动态生成数据库所有表Insert语句
    EasyUI combobox
    Linq使用Group By 1
  • 原文地址:https://www.cnblogs.com/0x10-lexsblog/p/14220021.html
Copyright © 2011-2022 走看看