Get image from server and preview it on client

血红的双手。 提交于 2019-12-22 10:55:45

问题


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 ?
}); 

Thank you.


回答1:


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;


来源:https://stackoverflow.com/questions/44611047/get-image-from-server-and-preview-it-on-client

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!