首页 > 其他 > 详细

下载文件

时间:2021-01-09 00:35:56      阅读:32      评论:0      收藏:0      [点我收藏+]

代码

@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();
}

测试

技术分享图片

下载文件

原文:https://www.cnblogs.com/shenleg/p/14253417.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!