Download an image using Axios and convert it to base64

后端 未结 3 809
忘了有多久
忘了有多久 2020-11-29 02:11

I need to download a .jpg image from a remote server and convert it into a base64 format. I\'m using axios as my HTTP client. I\'ve tried issuing a git request to the server

相关标签:
3条回答
  • 2020-11-29 02:39

    This is what works for me (with Buffer.from) -

    axios
      .get(externalUrl, {
        responseType: 'arraybuffer'
      })
      .then(response => {
        const buffer = Buffer.from(response.data, 'base64');
      })
      .catch(ex => {
        console.error(ex);
      });
    
    0 讨论(0)
  • 2020-11-29 02:54

    There might be a better way to do this, but I have done it like this (minus the extra bits like catch(), etc.):

    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);
    
            }
        });
    

    I have a suspicion that at least part of your problem might be server-side. Even without setting { responseType: "blob" } you should have had something in your response.data output.

    0 讨论(0)
  • 2020-11-29 02:56

    This worked great for me:

    function getBase64(url) {
      return axios
        .get(url, {
          responseType: 'arraybuffer'
        })
        .then(response => Buffer.from(response.data, 'binary').toString('base64'))
    }
    
    0 讨论(0)
提交回复
热议问题