【问题标题】:Download an image using Axios and convert it to base64使用 Axios 下载图像并将其转换为 base64
【发布时间】:2017-06-10 08:13:40
【问题描述】:

我需要从远程服务器下载 .jpg 图像并将其转换为 base64 格式。我使用 axios 作为我的 HTTP 客户端。我尝试向服务器发出 git 请求并检查response.data,但它似乎不像那样工作。

链接到 axios:https://github.com/mzabriskie/axios

base64 实现链接:https://www.npmjs.com/package/base-64

我正在使用 NodeJS / React,所以 atob/btoa 不起作用,因此该库。

axios.get('http://placehold.it/32').then(response => {
    console.log(response.data); // Blank
    console.log(response.data == null); // False 
    console.log(base64.encode(response.data); // Blank
}).catch(err => console.log(err));

【问题讨论】:

  • 您是否尝试将 responseType 更改为 blob? From docs "// responseType 表示服务器将响应的数据类型"

标签: javascript axios


【解决方案1】:

您可以将blob从FileReader api转换为base64然后显示。

 const fileReaderInstance = new FileReader();
 fileReaderInstance.readAsDataURL(blob); 
 fileReaderInstance.onload = () => {
 base64data = fileReaderInstance.result;                
 console.log(base64data);
 }

并将其显示为:

   <Image source={{uri: base64ImageData}} />

【讨论】:

    【解决方案2】:

    这对我很有用:

    function getBase64(url) {
      return axios
        .get(url, {
          responseType: 'arraybuffer'
        })
        .then(response => Buffer.from(response.data, 'binary').toString('base64'))
    }
    

    【讨论】:

    • 这很好用!如果可以的话,我会投票 100 次!
    • 如果您使用的是react-native,请将其添加到文件顶部:global.Buffer = global.Buffer || require('buffer').Buffer
    • 谢谢,效果很好!如果您将 base64 放在
    • 弃用警告:由于安全性和可用性问题,不推荐使用 Buffer()。请改用 Buffer.alloc()、Buffer.allocUnsafe() 或 Buffer.from() 方法。
    • 应该是 Buffer.from(response.data, 'binary'))
    【解决方案3】:

    这对我有用(Buffer.from)-

    axios
      .get(externalUrl, {
        responseType: 'arraybuffer'
      })
      .then(response => {
        const buffer = Buffer.from(response.data, 'base64');
      })
      .catch(ex => {
        console.error(ex);
      });
    

    【讨论】:

    • responseType: 'arraybuffer' 是我所需要的!
    【解决方案4】:

    可能有更好的方法可以做到这一点,但我已经这样做了(减去catch()等额外的位):

    axios.get(imageUrl, { responseType:"blob" })
        .then(function (response) {
    
            var reader = new window.FileReader();
            reader.readAsDataURL(response.data); 
            reader.onload = function() {
    
                var imageDataUrl = reader.result;
                imageElement.setAttribute("src", imageDataUrl);
    
            }
        });
    

    我怀疑您的问题至少有一部分可能出在服务器端。即使没有设置{ responseType: "blob" },您的response.data 输出中也应该有一些内容。

    【讨论】:

    • 搜索了几个小时后,我找到了解决方案。谢谢!!
    猜你喜欢
    • 1970-01-01
    • 2018-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多