springMVC文件下载

1、编写 java 实现

在这里插入图片描述

@Controller
public class FileController {
    @RequestMapping("/download")
    public ResponseEntity<byte[]> download(HttpSession session) throws IOException {
        // 获取ServletContext对象
        ServletContext context = session.getServletContext();
        // 获取服务器中文件的真实路径
        String path = context.getRealPath("static/img/computer.png");
        // 获取该文件的输入流
        FileInputStream inputStream = new FileInputStream(path);
        // 创建字节数组
        byte[] bytes = new byte[inputStream.available()];
        // 将输入流读到字节数组中
        inputStream.read(bytes);
        // 创建HttpHeaders对象设置响应头信息
        MultiValueMap<String, String> headers = new HttpHeaders();
        // 设置文件下载方式以及下载文件的名字
        headers.add("Content-Disposition","attachment;filename="+ URLEncoder.encode("图片.png","UTF-8"));
        // 设置响应报文的状态码
        HttpStatus status = HttpStatus.OK;
        // 创建ResponseEntity对象设置响应报文
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers, status);
        // 关闭输入流
        inputStream.close();
        return  responseEntity;
    }
}

2、html

index.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<a th:href="@{/download}">下载</a>
</body>
</html>

3、演示

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

文件下载(servlet)