SpringMVC实现文件上传&下载功能
文件上传
说明:
使用maven
构建web工程。
使用Thymeleaf
技术进行服务器页面渲染。
使用ResponseEntity
实现下载文件的功能。
@Controller public class FileDownloadAndUpload { @GetMapping("/file/download") public ResponseEntity<byte[]> fileDownload(HttpSession session) { //获取servletContext对象 ServletContext servletContext = session.getServletContext(); /* 路径空串:maven工程中获取的是当前web工程target下的war包路径 D:\spring-workspace\springmvc-pro\springmvc-filedownupload\target\springmvc-filedownupload-1.0-SNAPSHOT */ //String realPath = servletContext.getRealPath(""); //获取服务器中文件的真实路径 String path = File.separator + "imgs" + File.separator + "dog.jpg"; String realPath = servletContext.getRealPath(path); ResponseEntity<byte[]> responseEntity = null; try ( //创建字节输入流 BufferedInputStream bis = new BufferedInputStream(new FileInputStream(realPath)) ) { //创建字节数组 byte[] buff = new byte[bis.available()]; //将流读入到字节数组中 bis.read(buff); //创建HttpHeaders对象设置响应头信息 MultiValueMap<String, String> headers = new HttpHeaders(); //设置要下载方式以及下载文件的名字 headers.add("Content-Disposition", "attachment;filename=dog.jpg"); //设置响应状态码 HttpStatus statusCode = HttpStatus.OK; //创建ResponseEntity对象 responseEntity = new ResponseEntity<>(buff, headers, statusCode); return responseEntity; } catch (IOException e) { e.printStackTrace(); } throw new RuntimeException("文件下载出现异常"); } }
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>文件上传</title> </head> <body> <a th:href="@{/file/download}">文件下载</a><br/> </body> </html>
文件下载
文件上传要求form表单的请求方式必须为post
,并且添加属性enctype="multipart/form-data"
。
SpringMVC中将上传的文件封装到MultipartFile
对象中,通过此对象可以获取文件相关信息。
实现文件下载步骤:
step 1: 添加依赖
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.3</version> </dependency>
step 2:在springmvc配置文件中添加文件解析器
<!-- 通过文件解析器的解析才能将文件转换为MultipartFile对象,并且id必须为multipartResolver --> <bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver" />
setp 3:编写文件下载逻辑
@Controller public class FileDownloadAndUpload { @PostMapping("/file/upload") public String fileUpload(@RequestParam("photo") MultipartFile photo, HttpSession session) { //获取servletContext对象 ServletContext servletContext = session.getServletContext(); //获取上传文件的文件名 String filename = photo.getOriginalFilename(); //文件重命名问题 if (filename != null) { //获取文件后缀 String suffixFileName = filename.substring(filename.lastIndexOf(".")); //通过UUID重命名文件名 filename = UUID.randomUUID().toString() + suffixFileName; } //获取服务器中文件所在路径 String realPath = servletContext.getRealPath("imgs"); File file = new File(realPath); //判断文件目录是否存在 if (!file.exists()) { file.mkdir(); } //文件最终上传的路径 String filePath = realPath + File.separator + filename; //实现上传 try { photo.transferTo(new File(filePath)); } catch (IOException e) { e.printStackTrace(); } return "success"; } }
step 4:编写form表单
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>文件下载</title> </head> <body> <form th:action="@{/file/upload}" method="post" enctype="multipart/form-data"> <input type="file" name="photo"><br/> <input type="submit" value="点击上传"><br/> </form> </body> </html>
分类:
Java / Spring全家桶
标签:
Spring
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· 没有源码,如何修改代码逻辑?
· NetPad:一个.NET开源、跨平台的C#编辑器
· 面试官:你是如何进行SQL调优的?