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(); } }
三:服務(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)文章
Java Collection和Collections的區(qū)別
本文主要介紹了Java Collection和Collections的區(qū)別,Collection?是表示集合的接口,而?Collections?是對集合進(jìn)行操作的工具類,下面就來介紹一下具體用法,感興趣的可以了解一下2023-12-12Java給實體每一個字段賦默認(rèn)值詳細(xì)代碼示例
這篇文章主要給大家介紹了關(guān)于Java給實體每一個字段賦默認(rèn)值的相關(guān)資料,在編程過程中有時會出現(xiàn)這樣一種情況,在查詢無結(jié)果時我們需要給實體賦默認(rèn)值,需要的朋友可以參考下2023-09-09Spring?Boot?2.6.x整合Swagger啟動失敗報錯問題的完美解決辦法
這篇文章主要給大家介紹了關(guān)于Spring?Boot?2.6.x整合Swagger啟動失敗報錯問題的完美解決辦法,文中通過實例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2022-03-03使用Springboot+poi上傳并處理百萬級數(shù)據(jù)EXCEL
這篇文章主要介紹了使用Springboot+poi上傳并處理百萬級數(shù)據(jù)EXCEL,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-12-12