当前位置: 代码网 > it编程>编程语言>Java > java http请求获取图片并返回文件流给前端的方法步骤

java http请求获取图片并返回文件流给前端的方法步骤

2024年09月13日 Java 我要评论
需求 :在spring boot项目中实现获取外部http地址的图片,并返回文件流给前端一:依赖<!--web 模块--><dependency><groupid>

需求 :

在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请求获取图片返回文件流内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com