Mes*_*ded 3 javascript ajax reactjs axios
因此,我正在尝试从服务器获取图像并在客户端上预览它,我现在可以检索该图像,但是我不知道如何异步在网页上预览它。
axios.get(link,{responseType:'stream'}).then(img=>{
// What i have to do here ?
});
Run Code Online (Sandbox Code Playgroud)
谢谢。
首先,您需要使用响应类型获取图像arraybuffer。然后,您可以将结果转换为base64字符串,并将其分配为srcimage标签。这是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;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3983 次 |
| 最近记录: |