使用Springboot获取本地图片字节流,传入前端显示

参考网站:

使用Springboot获取本地图片字节流,传入前端显示 - 简书 (jianshu.com)

Returning an Image or a File with Spring | Baeldung中文网 (baeldung-cn.com)

需求

前端请求,传入一个用户头像 ID,后端 SpringBoot 根据该 ID 查询第三方服务接口,然后把结果返回给前端。

导包

1
2
3
4
5
6
7
8
9
10
11
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>

代码

Controller

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import org.apache.commons.io.IOUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import java.io.IOException;
import java.io.InputStream;

@RestController
@RequestMapping("/testController")
public class TestController{
private final TestService testService;

@GetMapping(value = "/getUserAvatar", produces = MediaType.IMAGE_JPEG_VALUE)
public ResponseEntity<byte[]> getUserAvatarById(@RequestParam("userAvatarId") @ApiParam("用户ID") String userAvatarId) throws IOException {
InputStream in = testService.getUserAvatar(userAvatarId);
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_JPEG);
return new ResponseEntity<>(IOUtils.toByteArray(in), headers, HttpStatus.OK);
}
}

Service

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
import okhttp3.MediaType;
import okhttp3.ResponseBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import retrofit2.Response;

import java.io.IOException;
import java.io.InputStream;

@Service
public class TestServiceImpl implements TestService{
private static final Logger logger = LoggerFactory.getLogger(TestServiceImpl.class);

private final TestApiClient apiClient;

@Override
public InputStream getUserAvatar(String userAvatarId) throws IOException {
Response<ResponseBody> response = apiClient.getUserAvatar(userAvatarId);
ResponseBody body = response.body();
if (body == null) {
return InputStream.nullInputStream();
}
MediaType mediaType = body.contentType();
if (mediaType != null && mediaType.type().contains("image")) {
return body.byteStream();
}
logger.warn("getUserAvatar failure by userAvatarId = {}. {}", userAvatarId, body.string());
return InputStream.nullInputStream();
}
}





  • 版权声明: 本博客所有文章除特别声明外,著作权归作者所有。转载请注明出处!
  • Copyrights © 2022-2024 Liangxj
  • 访问人数: | 浏览次数: