2017-06-18 93 views
1

所以我試圖從服務器獲取圖像並在客戶端上預覽它,我現在可以檢索圖像,但是我不知道如何預覽它一個網頁異步。從服務器獲取圖像並在客戶端上預覽

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

謝謝。

+0

我認爲簡單地將一個'src'值設置爲''將會容易得多。像''應該足夠好。如果你這樣做,瀏覽器會爲你加載圖像。 – DonovanM

+0

謝謝,但這不是我所需要的 –

+0

對不起,我想我誤解了你。你究竟想要做什麼?這聽起來像你試圖通過Ajax加載圖像,然後顯示它? – DonovanM

回答

1

首先,您需要使用響應類型arraybuffer獲取圖像。然後,您可以將結果轉換爲base64字符串,並將其指定爲圖像標記的src。這是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

你是最棒的! –

相關問題