温馨提示×

springboot怎么读取本地图片

小亿
201
2023-10-28 03:30:26
栏目: 编程语言

Spring Boot提供了一种简单的方式来读取本地图片。可以按照以下步骤操作:

  1. 在Spring Boot项目的资源目录(src/main/resources)下创建一个文件夹,用于存放图片文件。

  2. 将图片文件复制到刚创建的文件夹中。

  3. 在Spring Boot的配置文件(application.properties或application.yml)中配置图片文件的路径。例如,如果文件夹名为images,则可以在配置文件中添加以下内容:

    image.path=classpath:/images/
    

    或者

    image:
      path: classpath:/images/
    
  4. 在需要读取图片的地方,可以使用ResourceLoader来获取图片文件的路径。例如,在Controller中可以注入ResourceLoader,然后使用它来加载图片文件,如下所示:

    @RestController
    public class ImageController {
    
        @Autowired
        private ResourceLoader resourceLoader;
    
        @GetMapping("/image/{fileName}")
        public ResponseEntity<Resource> getImage(@PathVariable String fileName) throws IOException {
            Resource resource = resourceLoader.getResource("classpath:/images/" + fileName);
    
            return ResponseEntity.ok()
                    .contentType(MediaType.IMAGE_JPEG)
                    .body(resource);
        }
    }
    

    上面的例子中,请求/image/{fileName}将会返回对应的图片文件。

通过以上步骤,你就可以在Spring Boot项目中读取本地图片了。

0