SpringBoot的文件下载
关于文件上传和下载,其实都挺简单的。pom文件主要的如下。(这里这个fileupload可以不下,可以自己选择写其他的方法下载,不一定参考我的,我的是Spring MVC通过阿帕奇Commons FileUpload技术实现的一个实现类,所以才需要依赖这个组件)
<dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.3</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
我这里写的下载是先从自己的存储下载文件里查出有多少文件并且显示在前端页面。
下载文件点此处
控制层代码: //下载页面展示
@RequestMapping("/showDownLoad")
public String showDownLoad(HttpServletRequest request, Model model){
String path = “E:\Web\UploadDownLoad”;
//request.getServletContext().getRealPath("/upload333");
File fileDir = new File(path);
File filesList[] = fileDir.listFiles();
System.out.println(path);
model.addAttribute(“filesList”,filesList);
model.addAttribute(“hanhan”,“123456”);
return “downLoad”;
} //下载 @GetMapping("/downLoad") public ResponseEntity<byte[]> downloadFile(HttpServletRequest request, @RequestParam("filename") String filename)throws IOException { //@RequestHeader("User - Agent") String userAgent String path = "E:\\Web\\UploadDownLoad"; //request.getServletContext().getRealPath("/upload333"); File downFile = new File(path + File.separator + filename); ResponseEntity.BodyBuilder builder = ResponseEntity.ok(); builder.contentLength(downFile.length()); builder.contentType(MediaType.APPLICATION_OCTET_STREAM); filename = URLEncoder.encode(filename,"UTF-8");
// !!!! 本来是想使用UA进行使用浏览器区别对待的,一直报错,400,我暂时也不知道前端怎么传,那就暂且把这个问题放一边叭
// if(userAgent.indexOf(“MSIE”)>0){
// builder.header(“Content-Disposition”,“attachment;filename=”+filename);
//
// }else{
// builder.header(“Content-Disposition”,“attachment;filename*=UTF-8’’”+filename);
// }
return builder.body(FileUtils.readFileToByteArray(downFile));
}
前端html代码如下:这里是接收控制层的参数并以视图显示出来。
<span th:text="${fileStat.count}"></span> </td> <td> <a th:href="@{downLoad(filename = ${file.name})}"> <span th:text="${file.name}"></span> </a> </td> </tr> </tbody> </table> </div> 然后效果如下,点击链接即可下载至本地。 ![在这里插入图片描述](https://www.www.zyiz.net/i/ll/?i=e95ab41404404e3f86f5fd9f0305e049.png?,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBAcXFfNDI3MzgzODc=,size_20,color_FFFFFF,t_70,g_se,x_16#pic_center)