springboot中需要动态加载图片,该如何做,调用的图应该放在哪里,以及如何查询图片
时间: 2024-01-28 10:05:31 浏览: 34
在Spring Boot中,如果要动态加载图片,可以将图片文件放在项目的静态资源目录下,一般默认是`src/main/resources/static`目录下。
然后在需要使用的地方,可以使用`org.springframework.core.io.Resource`来表示这个图片资源。可以使用`org.springframework.core.io.ClassPathResource`来获取静态资源目录下的文件,也可以使用`org.springframework.core.io.FileSystemResource`获取文件系统上的文件。
下面是一个简单的示例,演示如何从静态资源目录下加载一张图片:
```java
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.io.IOException;
import java.io.InputStream;
@Controller
public class ImageController {
@GetMapping(value = "/image")
@ResponseBody
public ResponseEntity<byte[]> getImage() throws IOException {
Resource resource = new ClassPathResource("static/myimage.png");
InputStream inputStream = resource.getInputStream();
byte[] bytes = new byte[inputStream.available()];
inputStream.read(bytes);
return ResponseEntity.ok().contentType(MediaType.IMAGE_PNG).body(bytes);
}
}
```
上面的示例中,`ClassPathResource`表示从类路径下加载文件,其中`"static/myimage.png"`表示静态资源目录下的`myimage.png`文件。然后使用`InputStream`读取文件内容,最后返回`ResponseEntity`,将文件内容作为图片响应给客户端。
需要注意的是,如果是部署在Web容器中,还需要配置Web容器,将静态资源目录映射到对应的URL路径上。在Spring Boot中,可以使用`WebMvcConfigurer`来配置静态资源目录映射。例如,可以在`application.properties`中添加以下配置:
```
spring.mvc.static-path-pattern=/static/**
spring.resources.static-locations=classpath:/static/
```
其中,`spring.mvc.static-path-pattern`表示URL路径前缀,`spring.resources.static-locations`表示静态资源目录。上面的示例中,图片的URL路径为`/static/myimage.png`。