springboot系列16:文件上传
文件上传用到的场景也比较多,如头像的修改、相册应用、附件的管理等等,今天就来学习下在springboot框架下应用文件上传技术。
1、pom 配置
1 2 3 4 5 6 7 8 9 10 | <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> </dependencies> |
2、application.properties配置上传文件的大小
1 2 | spring.servlet.multipart.max-file-size=10MB spring.servlet.multipart.max-request-size=10MB |
3、上传页面
1 2 3 4 5 6 7 8 9 10 | <!DOCTYPE html> <html xmlns:th= "http://www.thymeleaf.org" > <body> <h1>Spring Boot file upload example</h1> <form method= "POST" action= "/upload" enctype= "multipart/form-data" > <input type= "file" name= "file" /><br/><br/> <input type= "submit" value= "上传" /> </form> </body> </html> |
4、上传结果页面
1 2 3 4 5 6 7 8 9 | <!DOCTYPE html> <html lang= "en" xmlns:th= "http://www.thymeleaf.org" > <body> <h1>SpringBoot - 文件上传结果</h1> <div th: if = "${message}" > <h2 th:text= "${message}" /> </div> </body> </html> |
5、上传文件controller
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | @Controller public class UploadController { private static String UPLOADED_FOLDER = "E://temp//" ; @GetMapping ( "/" ) public String index() { return "index" ; } @PostMapping ( "/upload" ) public String singleFileUpload( @RequestParam ( "file" ) MultipartFile file, RedirectAttributes redirectAttributes) { if (file.isEmpty()) { redirectAttributes.addFlashAttribute( "message" , "请选择一个文件上传" ); return "redirect:uploadStatus" ; } try { byte [] bytes = file.getBytes(); File pathFile = new File(UPLOADED_FOLDER); if (!pathFile.exists()){ pathFile.mkdirs(); } Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename()); Files.write(path, bytes); redirectAttributes.addFlashAttribute( "message" , "文件上传成功:'" + file.getOriginalFilename() + "'" ); } catch (IOException e) { e.printStackTrace(); } return "redirect:/result" ; } @GetMapping ( "/result" ) public String result() { return "result" ; } } |
分类:
spring boot
标签:
spring
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决