Java Springboot Resources目录下文件获取失败问题

近日需要提供一个模板下载接口,本地ok,提交代码时想着,方法里的文件是我Windows系统上的路径,想着把文件挪到resource目录下,挪动后,自测,nullPoint,我就开始看这个问题了。

先说结论:代码无异常,执行maven clean,清理了target文件夹后,代码就跑起来了。预估是重新启动这个微服务也好,还是我在controller类中新增的psvm代码块,人家IDEA压根没把我新建的文件编译至target目录中,所以就直接说找不到,报异常。

获取文件的两种方法: 

 ClassPathResource resource = new ClassPathResource("template/" + "批量导入模板.xlsx");

FileSystemResource resource = new FileSystemResource("template/批量导入模板");

这两种方法都可以获取到相对路径中的文件,拿到resource后,无论是获取文件还是IO流都是很方便的,剩下的操作就看人家提供了啥子api了。祝君好运,少怀疑自己,多质问下IDEA!多看看是不是缓存与编译问题!

  • 10
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot项目的文件上传模块主要涉及到两个方面:前端页面的选择文件和提交表单,以及后端的文件上传处理。 前端页面部分: 1. 在HTML页面中添加一个表单,用于文件上传: ```html <form method="POST" enctype="multipart/form-data" action="/upload"> <div class="form-group"> <label for="file">选择文件:</label> <input type="file" name="file" id="file"> </div> <button type="submit" class="btn btn-primary">上传</button> </form> ``` 2. 在Spring Boot的Controller中处理文件上传请求: ```java @PostMapping("/upload") public String uploadFile(@RequestParam("file") MultipartFile file) { // 获取文件名 String fileName = file.getOriginalFilename(); // 获取文件存储路径 String filePath = "D:/upload/"; try { // 将文件保存到指定路径 file.transferTo(new File(filePath + fileName)); return "上传成功!"; } catch (IOException e) { e.printStackTrace(); } return "上传失败!"; } ``` 后端部分: 1. 在pom.xml中添加依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> ``` 2. 在Spring Boot的启动类上添加注解@EnableWebMvc: ```java @SpringBootApplication @EnableWebMvc public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 3. 在Controller中添加@RequestMapping注解和处理文件上传请求的方法: ```java @Controller public class FileUploadController { @RequestMapping("/upload") public String fileUpload(@RequestParam("file") MultipartFile file, Model model) { // 获取文件名 String fileName = file.getOriginalFilename(); // 获取文件存储路径 String filePath = "D:/upload/"; try { // 将文件保存到指定路径 file.transferTo(new File(filePath + fileName)); model.addAttribute("msg", "上传成功!"); } catch (IOException e) { e.printStackTrace(); model.addAttribute("msg", "上传失败!"); } return "uploadResult"; } } ``` 4. 添加视图解析器,用于返回上传结果页面: ```java @Configuration public class MvcConfig implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/uploadResult").setViewName("uploadResult"); } } ``` 5. 在resources/templates/目录下添加上传结果页面uploadResult.html: ```html <!DOCTYPE html> <html> <head> <title>上传结果</title> </head> <body> <h1 th:text="${msg}"></h1> </body> </html> ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值