javascript - 如何将图像数据响应转换为 Image base64?

标签 javascript reactjs axios

这是我的 api
https://besticon-demo.herokuapp.com/icon?url=facebook.com&size=80..120..200
当我在 postman 中测试这个时,我得到了图像..但是我怎么能用 axios .
我现在正在使用 Axios 获得很长的字符串(如�PNG...)
那么我如何使用该响应来显示图像..

   axios.get(RequestURL, { withCredentials: false })
                .then(function (response) {
                    // handle success
                    console.log(response)
                    var b64Response = btoa(response.data) 
                    setImageServer('data:image/png;base64,' + b64Response) // not showing image
                })
尝试运行时也会出错 btoa

DOMException: Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.


HTML
 <img src={ImageServer}/>

最佳答案

axios.get('RequestURL', { responseType: 'arraybuffer' })
.then(response => {
      let blob = new Blob(
        [response.data], 
        { type: response.headers['content-type'] }
      )
      let image = window.URL.createObjectURL(blob)
      return image
    })
axios.get('RequestURL', {responseType: 'blob'})
.then(response => {
  let imageNode = document.getElementById('image');
  let imgUrl = URL.createObjectURL(response.data)
  imageNode.src = imgUrl
})

关于javascript - 如何将图像数据响应转换为 Image base64?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67389889/

相关文章:

vue.js - 发出 Axios 请求时加载微调器

javascript - 如何包装包含在方括号内的内容,在所有出现的字符串中全局使用 span 标记?

javascript - Angular 智能表不起作用

javascript - 如何在 Gatsby 中使用带有富文本的内联图像?

reactjs - 如何使用 create-react-app 创建包含 Web3 的 React App?我收到模块未找到错误。重大变化 : webpack < 5 used

javascript - 在 Vue js 中导入 axios 方法的正确语法

java - Servlet 响应未显示在网页上

javascript - 棘手的 Javascript 正则表达式替换

javascript - 使用 Typescript 通过 getInitialProps 将 prop 传递到 Next.js 中的每个页面

javascript - express get url 错误