需求 :
在spring boot项目中实现获取外部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(); } }
三:服务实现类
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,根据实际情况调整 // 发送http请求获取图片数据流 responseentity<byte[]> imageresponse = resttemplate.exchange(imageurl, httpmethod.get, new httpentity<>(headers), byte[].class); // 将图片数据流写入响应输出流 if (imageresponse.getstatuscode() == httpstatus.ok && imageresponse.getbody() != null) { response.setcontenttype(mediatype.image_jpeg_value); // 设置响应内容类型 response.getoutputstream().write(imageresponse.getbody()); // 将图片数据写入响应输出流 } else { response.setstatus(httpstatus.not_found.value()); // 处理请求失败的情况 } } }
可以用postman测试一下效果:
总结
到此这篇关于java http请求获取图片并返回文件流给前端的文章就介绍到这了,更多相关java http请求获取图片返回文件流内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论