前言
文件下载: 将服务器某个资源文件下载到用户本地计算机过程称之为文件下载
用户通过浏览器访问页面,点击链接之后,就能从服务器下载本地中。
具体思路:
a.确定项目中哪些资源可以被下载 aa.txt 用户须知.doc …
b.将可以被下载资源放入服务器指定位置 、文件上传服务器fastdfs(dfs 分布式文件存储系统 1000个节点 冗余备份 )
c.项目中开发一个下载页面download.jsp
提供下载文件链接
d.开发下载控制器controller
建立download目录
我们会在本项目中建立一个download目录
提供文件下载链接
<h1>测试文件下载</h1><a href="${pageContext.request.contextPath}/file/download?fileName=Hello.html">Hello.html</a><a href="${pageContext.request.contextPath}/file/download?fileName=项目日记.md">项目日记.md</a>
</body>
开发控制器
@Controller
@RequestMapping("file")
public class FileController {private static final Logger log = LoggerFactory.getLogger(FileController.class);//这里是用文件注入的方式来表示文件目录的。@Value("${file.download.dir}")private String realPath;/*** 文件下载* @param fileName*/@RequestMapping("download")public void download(String fileName, HttpServletResponse response) throws IOException {log.debug("当前下载文件名为: {}",fileName);log.debug("当前下载文件目录: {}",realPath);//1.去指定目录中读取文件File file = new File(realPath, fileName);//2.将文件读取为文件输入流FileInputStream is = new FileInputStream(file);//2.5 获取响应流之前 一定要设置以附件形式下载 attachment:附件response.setHeader("content-disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));//3.获取响应输出流ServletOutputStream os = response.getOutputStream();//4.输入流复制给输出流/*int len=0;byte[] b = new byte[1024];while(true){len = is.read(b);if(len==-1)break;os.write(b,0,len);}*/FileCopyUtils.copy(is,os);}}
application.yml
file:download:dir: D:\\Study\\java\\practical-projects\\spring-boot\\springbootTest5\\download #指定下载目录测试环境