0


java http请求获取图片并返回文件流给前端

需求 :在Spring Boot项目中实现获取外部HTTP地址的图片,并返回文件流给前端

一:依赖

  1. <!--web 模块-->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-web</artifactId>
  5. </dependency>

二:配置类

  1. import org.springframework.context.annotation.Bean;
  2. import org.springframework.context.annotation.Configuration;
  3. import org.springframework.web.client.RestTemplate;
  4. @Configuration
  5. public class RestTemplateConfig {
  6. @Bean(name = "restTemplateJQSJ")
  7. public RestTemplate restTemplate(){
  8. return new RestTemplate();
  9. }
  10. }

三:服务实现类

  1. import org.springframework.http.*;
  2. import org.springframework.web.bind.annotation.*;
  3. import org.springframework.web.client.*;
  4. import javax.servlet.http.HttpServletResponse;
  5. import java.io.*;
  6. @RestController
  7. @RequestMapping("/api")
  8. public class ImageController {
  9. @Autowired
  10. @Qualifier("restTemplateJQSJ")
  11. private RestTemplate restTemplate;
  12. @GetMapping("/image")
  13. public void getImage(HttpServletResponse response) throws IOException {
  14. String imageUrl = "http://获取图片的地址";
  15. // 设置HTTP头部信息
  16. HttpHeaders headers = new HttpHeaders();
  17. headers.setContentType(MediaType.IMAGE_JPEG); // 假设图片类型为JPEG,根据实际情况调整
  18. // 发送HTTP请求获取图片数据流
  19. ResponseEntity<byte[]> imageResponse = restTemplate.exchange(imageUrl, HttpMethod.GET, new HttpEntity<>(headers), byte[].class);
  20. // 将图片数据流写入响应输出流
  21. if (imageResponse.getStatusCode() == HttpStatus.OK && imageResponse.getBody() != null) {
  22. response.setContentType(MediaType.IMAGE_JPEG_VALUE); // 设置响应内容类型
  23. response.getOutputStream().write(imageResponse.getBody()); // 将图片数据写入响应输出流
  24. } else {
  25. response.setStatus(HttpStatus.NOT_FOUND.value()); // 处理请求失败的情况
  26. }
  27. }
  28. }

可以用Postman测试一下效果:

标签: java http 前端

本文转载自: https://blog.csdn.net/m0_57038084/article/details/139958211
版权归原作者 洛可可Blue 所有, 如有侵权,请联系我们删除。

“java http请求获取图片并返回文件流给前端”的评论:

还没有评论