java?http請求獲取圖片并返回文件流給前端的方法步驟
更新時間:2024年09月13日 11:28:11 作者:洛可可Blue
作為一名Java后端開發(fā)者,掌握如何從后端返回文件流至前端是基本技能之一,這篇文章主要介紹了java?http請求獲取圖片并返回文件流給前端的方法步驟,需要的朋友可以參考下
需求 :
在Spring Boot項目中實現(xiàn)獲取外部HTTP地址的圖片,并返回文件流給前端
一:依賴
<!--web 模塊--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
二:配置類
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestTemplateConfig {
@Bean(name = "restTemplateJQSJ")
public RestTemplate restTemplate(){
return new RestTemplate();
}
}三:服務實現(xiàn)類
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.*;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
@RestController
@RequestMapping("/api")
public class ImageController {
@Autowired
@Qualifier("restTemplateJQSJ")
private RestTemplate restTemplate;
@GetMapping("/image")
public void getImage(HttpServletResponse response) throws IOException {
String imageUrl = "http://獲取圖片的地址";
// 設置HTTP頭部信息
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_JPEG); // 假設圖片類型為JPEG,根據(jù)實際情況調(diào)整
// 發(fā)送HTTP請求獲取圖片數(shù)據(jù)流
ResponseEntity<byte[]> imageResponse = restTemplate.exchange(imageUrl, HttpMethod.GET, new HttpEntity<>(headers), byte[].class);
// 將圖片數(shù)據(jù)流寫入響應輸出流
if (imageResponse.getStatusCode() == HttpStatus.OK && imageResponse.getBody() != null) {
response.setContentType(MediaType.IMAGE_JPEG_VALUE); // 設置響應內(nèi)容類型
response.getOutputStream().write(imageResponse.getBody()); // 將圖片數(shù)據(jù)寫入響應輸出流
} else {
response.setStatus(HttpStatus.NOT_FOUND.value()); // 處理請求失敗的情況
}
}
}可以用Postman測試一下效果:

總結
到此這篇關于java http請求獲取圖片并返回文件流給前端的文章就介紹到這了,更多相關java http請求獲取圖片返回文件流內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Springdoc替換swagger的實現(xiàn)步驟分解
最近在spring看到的,spring要對api文檔動手了,有些人說swagger不好用,其實也沒那么不好用,有人說代碼還是有點侵入性,這倒是真的,我剛試了springdoc可以說還是有侵入性但是也可以沒有侵入性,這就看你對文檔有什么要求了2023-02-02
SpringBoot Maven打包插件spring-boot-maven-plugin無法解析原因
spring-boot-maven-plugin是spring boot提供的maven打包插件,本文主要介紹了SpringBoot Maven打包插件spring-boot-maven-plugin無法解析原因,具有一定的參考價值,感興趣的可以了解一下2024-03-03
解決SpringAop內(nèi)部調(diào)用時不經(jīng)過代理類的問題
這篇文章主要介紹了解決SpringAop內(nèi)部調(diào)用時不經(jīng)過代理類的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-01-01

