zoukankan      html  css  js  c++  java
  • 下载文件

    代码

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取要下载的文件的绝对路径
        String filePath = this.getServletContext().getRealPath("WEB-INF/classes/Surface Stusio default wallpaper.png");
        String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
        // 让浏览器识别这是一个下载文件,如果是浏览器支持的文件类型,一般会默认使用浏览器打开
        // 利用Content-Disposition处理提示下一步操作
        // 中文文件名用URLEncoder.encode编码,否则有可能乱码,同时解决空格变+号问题
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")
                .replace("+", "%20"));
        // 获取下载文件的输入流
        FileInputStream in = new FileInputStream(filePath);
        BufferedInputStream bis = new BufferedInputStream(in);
        // 获取输出流
        ServletOutputStream out = response.getOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(out);
        // 输入流 -> 输出流
        int len = 0;
        byte[] b = new byte[1024];
        while ((len = bis.read(b)) != -1) {
            bos.write(b, 0, len);
        }
        // 关闭自己创建的流
        bis.close();
        bos.close();
    }
    

    测试

  • 相关阅读:
    第三章 学习ICE 3.0Slice语言
    腾讯
    Websvn的安装
    fedora下装eclipse
    linux快捷键
    windows下SVN解决方案
    用ICE实现一个简单的聊天室
    Tortoise SVN 客户端使用方法
    GCC安装
    在VC++6.0 IDE中配置ICE工程[ ICE FOR VC++6.0 ]
  • 原文地址:https://www.cnblogs.com/shenleg/p/14253417.html
Copyright © 2011-2022 走看看