Springboot中设置response直接下载文件

需求: 前台点击链接,浏览器直接下载。

  1. 后台代码

    /**
     * 下载文件
     *
     * @param response 文件流
     * @throws Exception        流异常
     */
    @ApiModelProperty(value = "下载文件")
    @GetMapping("downFile")
    public void downFile(HttpServletResponse response) throws Exception {
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition", "attachment; fileName=" + fileInfo.getFullFileName());
        File file = new File("D:\\file\\1.jpg");
        byte[] bytes = Files.toByteArray(file);
        out.write(bytes);
        out.close();
    }

2.前台代码

<a href="http://127.0.0.1:8080/apis/file/downFile" rel="nofollow">下载文件</a>

3.整理

response在头部设置 "Content-Disposition" 为 "attachment; fileName= xxx" , xxx为文件名称,带后缀的文件名称,设置之后,文件下载的名称就直接是设置的名称;

猜你喜欢

转载自blog.csdn.net/qq_38821574/article/details/103593868
今日推荐