可以通过以下步骤实现:

  1. 在 Spring Boot 中配置静态资源路径,例如将图片存储在项目的 static/images 目录下,可以在 application.properties 中添加以下配置:

spring.resources.static-locations=classpath:/static/

  1. 创建一个 RESTful API 接口,用于返回图片 URL。可以使用 @RestController 注解来标记一个类,表示这个类是一个 RESTful 风格的控制器。

  2. 在控制器中,使用 @GetMapping 注解来标记一个方法,表示这个方法处理 GET 请求。在方法中,可以使用 Spring Boot 提供的 ResourceLoader 来加载图片资源,然后将图片的 URL 封装成一个 JSON 对象返回给前端。

以下是一个示例代码:

@RestController public class ImageController {

private final ResourceLoader resourceLoader;

public ImageController(ResourceLoader resourceLoader) {
    this.resourceLoader = resourceLoader;
}

@GetMapping("/image")
public Map<String, String> getImageUrl() throws IOException {
    Resource resource = resourceLoader.getResource("classpath:/static/images/test.jpg");
    String url = resource.getURL().toString();
    Map<String, String> result = new HashMap<>();
    result.put("url", url);
    return result;
}

}

在上面的代码中,我们将图片存储在 static/images/test.jpg 文件中,然后通过 ResourceLoader 加载图片资源,获取图片的 URL,并将 URL 封装成一个 JSON 对象返回给前端。前端可以通过访问 /image 接口来获取图片 URL。

springboot 如何实现前端直接获取图片封装成JSON后返回URL

原文地址: http://www.cveoy.top/t/topic/bFBU 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录