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ù)實際情況調整
// 發(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); // 設置響應內容類型
response.getOutputStream().write(imageResponse.getBody()); // 將圖片數(shù)據(jù)寫入響應輸出流
} else {
response.setStatus(HttpStatus.NOT_FOUND.value()); // 處理請求失敗的情況
}
}
}可以用Postman測試一下效果:

總結
到此這篇關于java http請求獲取圖片并返回文件流給前端的文章就介紹到這了,更多相關java http請求獲取圖片返回文件流內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Java Collection和Collections的區(qū)別
本文主要介紹了Java Collection和Collections的區(qū)別,Collection?是表示集合的接口,而?Collections?是對集合進行操作的工具類,下面就來介紹一下具體用法,感興趣的可以了解一下2023-12-12
Spring?Boot?2.6.x整合Swagger啟動失敗報錯問題的完美解決辦法
這篇文章主要給大家介紹了關于Spring?Boot?2.6.x整合Swagger啟動失敗報錯問題的完美解決辦法,文中通過實例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2022-03-03
使用Springboot+poi上傳并處理百萬級數(shù)據(jù)EXCEL
這篇文章主要介紹了使用Springboot+poi上傳并處理百萬級數(shù)據(jù)EXCEL,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-12-12

