随笔都是学习笔记
随笔仅供参考,为避免笔记中可能出现的错误误导他人,请勿转载。

请求处理方法:

    @RequestMapping("/download")
    public String download(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 获取下载文件路径
        String realPath = request.getServletContext().getRealPath("/img/img.png");
        // 将文件路径封装为File对象
        File path = new File(realPath);
        // 根据File对象获取文件名
        String fileName = path.getName();
        // 设置响应头:content-disposition 设置文件下载的打开方式,默认在网页上打开
        // 设置attachment;filename= 设置以下载的形式打开文件
        // "UTF-8" 设置编码,以防文件名称中的中文出现乱码
        response.setHeader("content-disposition","attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));
        InputStream in = new FileInputStream(realPath); // 文件输入流
        int len = 0;
        byte[] buffer = new byte[1024];
        OutputStream out = response.getOutputStream();
        while((len = in.read(buffer))>0){
            out.write(buffer,0,len);    // 将缓冲区的数据输出到客户端浏览器
        }
        in.close();
        return null;
    }

前端进行下载请求:

访问结果:

点击下载:

 

下载成功 

 

posted on 2022-06-29 17:33  时间完全不够用啊  阅读(94)  评论(0编辑  收藏  举报