最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get image from server and preview it on client - Stack Overflow

programmeradmin15浏览0评论

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.

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.

Share Improve this question asked Jun 18, 2017 at 1:48 FrenchTechLeadFrenchTechLead 1,1563 gold badges13 silver badges22 bronze badges 3
  • I think it would be much easier to simply set a src value to an <img> in react. Something like <img src={link} /> should be good enough. The browser will load the image for you if you do that. – DonovanM Commented Jun 18, 2017 at 2:19
  • thank you but it's not what i need – FrenchTechLead Commented Jun 18, 2017 at 3:27
  • Sorry, I guess I misunderstood you. What exactly are you trying to do? It sounded like you were trying to load an image over ajax and then display it? – DonovanM Commented Jun 18, 2017 at 3:33
Add a comment  | 

1 Answer 1

Reset to default 15

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;
发布评论

评论列表(0)

  1. 暂无评论