从服务器获取图像并在客户端预览 [英] Get image from server and preview it on client

查看:26
本文介绍了从服务器获取图像并在客户端预览的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图从服务器获取图像并在客户端上预览,我现在可以检索图像,但我不知道如何在网页上异步预览它.

So i'm trying to get an image from a server and previewing it on the client, i can retrieve the image for now, but i don't know how to preview it on a web page asynchronously.

axios.get(link,{responseType:'stream'}).then(img=>{
// What i have to do here ?
}); 

谢谢.

推荐答案

首先,您需要获取响应类型为 arraybuffer 的图像.然后您可以将结果转换为 base64 字符串并将其分配为图像标签的 src.这是 React 的一个小例子.

First, you need to fetch your image with the response type arraybuffer. Then you can convert the result to a base64 string and assign it as src of an image tag. Here is a small example with React.

import React, { Component } from 'react';
import axios from 'axios';

class Image extends Component {
  state = { source: null };

  componentDidMount() {
    axios
      .get(
        'https://www.example.com/image.png',
        { responseType: 'arraybuffer' },
      )
      .then(response => {
        const base64 = btoa(
          new Uint8Array(response.data).reduce(
            (data, byte) => data + String.fromCharCode(byte),
            '',
          ),
        );
        this.setState({ source: "data:;base64," + base64 });
      });
  }

  render() {
    return <img src={this.state.source} />;
  }
}

export default Image;

这篇关于从服务器获取图像并在客户端预览的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆