import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
@Controller
public class DownFile {
@RequestMapping("/download")
public void downFile(String fileName, HttpServletResponse res, HttpServletRequest req) throws IOException {
// 设置响应头
res.setHeader("Content-Disposition","attachment;filename=bbb.txt");
// 获取流对象
ServletOutputStream os = res.getOutputStream();
// 获取文件所在文件夹路径文件路径
String path = req.getSession().getServletContext().getRealPath("files");
// 获取File对象,文件路径 和文件名
File file = new File(path, fileName);
// 通过apache工具将文件转换为字节数据
byte[] bytes = FileUtils.readFileToByteArray(file);
// 写出
os.write(bytes);
os.flush();
os.close();
}
}
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.19.RELEASE</version>
</dependency>
<dependency>
<groupId>org.kie.modules</groupId>
<artifactId>org-apache-commons-fileupload</artifactId>
<version>6.5.0.Final</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
</dependencies>
@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<a href="download?fileName=a.txt">下载</a>
</body>
</html>