服务端读取图片内容返回前端,解决图片跨域问题

最近在配合前端开发,开发一个图片裁剪功能的时候,遇到一个oss图片跨域请求,无法访问的问题,索性自己写个接口,先读取图片文件流再直接返回前端。具体代码如下。

1.新建文件流内容封装类FileContent

 1 public class FileContent {
 2     private byte[] content;
 3     private String content_type;
 4 
 5     public byte[] getContent() {
 6         return content;
 7     }
 8 
 9     public void setContent(byte[] content) {
10         this.content = content;
11     }
12 
13     public String getContent_type() {
14         return content_type;
15     }
16 
17     public void setContent_type(String content_type) {
18         this.content_type = content_type;
19     }
20 }

2.根据图片链接获取文件流

public static FileContent getImageByte(String img){
        //String imgUrl="http://mmbiz.qpic.cn/mmbiz/yqVAqoZvDibEaicDyIvX7dLE9icYnwb2tlOtSzGMCglvqk61JjpW338xMSlJsKPVBiaD6FY1M5MtopJYvWrVYeYwFA/0?wx_fmt=jpeg";
        ByteArrayOutputStream outStream = null;
        FileContent file=new FileContent();
        String contentType="";
        try {
            URL url=new URL(img);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(10 * 1000);
            contentType=conn.getHeaderField("Content-Type");
            //通过输入流获取图片数据
            InputStream inStream = conn.getInputStream();

            outStream = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            int len = 0;
            while( (len=inStream.read(buffer)) != -1 ){
                outStream.write(buffer, 0, len);
            }
            inStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] content= outStream.toByteArray();
        file.setContent(content);
        file.setContent_type(contentType);

        return file;
    }

3.接口获取参数图片链接

 @RequestMapping("/read/image")
    public ResponseEntity<byte[]> getImageContent(HttpServletRequest request){
        HttpHeaders responseHeaders = new HttpHeaders();

        String imageUrl=request.getParameter("imageUrl");
        FileContent file=Utilities.getImageByte(imageUrl);

        responseHeaders.set("Access-Control-Allow-Origin","*");
        responseHeaders.set("Content-Type",file.getContent_type());

        return new ResponseEntity<>(file.getContent(), responseHeaders, HttpStatus.OK);
    }

4.前端可直接通过 域名+/read/image?imageUrl=XXXX调用网络图片,即可完美解决图片跨域问题。

转载于:https://www.cnblogs.com/kui-technology/p/9987117.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值