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();
}
}三:服務(wù)實現(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://獲取圖片的地址";
// 設(shè)置HTTP頭部信息
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_JPEG); // 假設(shè)圖片類型為JPEG,根據(jù)實際情況調(diào)整
// 發(fā)送HTTP請求獲取圖片數(shù)據(jù)流
ResponseEntity<byte[]> imageResponse = restTemplate.exchange(imageUrl, HttpMethod.GET, new HttpEntity<>(headers), byte[].class);
// 將圖片數(shù)據(jù)流寫入響應(yīng)輸出流
if (imageResponse.getStatusCode() == HttpStatus.OK && imageResponse.getBody() != null) {
response.setContentType(MediaType.IMAGE_JPEG_VALUE); // 設(shè)置響應(yīng)內(nèi)容類型
response.getOutputStream().write(imageResponse.getBody()); // 將圖片數(shù)據(jù)寫入響應(yīng)輸出流
} else {
response.setStatus(HttpStatus.NOT_FOUND.value()); // 處理請求失敗的情況
}
}
}可以用Postman測試一下效果:

總結(jié)
到此這篇關(guān)于java http請求獲取圖片并返回文件流給前端的文章就介紹到這了,更多相關(guān)java http請求獲取圖片返回文件流內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
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
關(guān)于SpringBoot改動后0.03秒啟動的問題
這篇文章主要介紹了SpringBoot改動后0.03秒啟動,本文結(jié)合示例代碼給大家講解的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-12-12
解決SpringAop內(nèi)部調(diào)用時不經(jīng)過代理類的問題
這篇文章主要介紹了解決SpringAop內(nèi)部調(diào)用時不經(jīng)過代理類的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-01-01
springboot+gradle 構(gòu)建多模塊項目的步驟
這篇文章主要介紹了springboot+gradle 構(gòu)建多模塊項目的步驟,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-05-05
使用Jenkins自動化構(gòu)建工具進(jìn)行敏捷開發(fā)
這篇文章主要為大家介紹了使用Jenkins自動化構(gòu)建工具進(jìn)行敏捷開發(fā),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步早日升職加薪2022-04-04

