使用AXIOS与laravel结合使用来显示图像URL

时间:2020-06-30 08:05:36

标签: php laravel axios

现在,我正在将AXIOS代码与laravel结合使用,以从instagram URL获取图像。 URL是这个https://www.instagram.com/p/B_zZCRpB895/media/?size=t

AXIOS是我的新手。为了得到图像,我尝试了这个简单的代码。我将此代码设置到我的前端站点中

<img id="imgsrc" src="" > 

<script>
 axios
  .get('https://www.instagram.com/p/B_zZCRpB895/media/?size=t', {
    responseType: 'arraybuffer'
  })
  .then(response => {
    const buffer = Buffer.from(response.data, 'base64');
    document.getElementById("imgsrc").src = Buffer;
    console.log(Buffer);  
  })
  .catch(ex => {
    console.error(ex);
  });
</script>

但图像未显示在<img id="imgsrc" src="" >

当我们打开页面时,我真的想要那个。 instagram图片可以显示。

如何解决此问题。请帮忙。

2 个答案:

答案 0 :(得分:1)

您可以使用文件阅读器获取base64并将其设置为图像源:

<script>
    axios.get('https://www.instagram.com/p/B_zZCRpB895/media/?size=t', {responseType: "blob"})
        .then(function (response) {
            var reader = new window.FileReader();
            reader.readAsDataURL(response.data);
            reader.onload = function () {
                document.getElementById("imgsrc").src = reader.result;
            }
        });
</script>

答案 1 :(得分:0)

您是否有特定原因要使用axios通过AJAX调用来检索它?

您提供的端点已经返回了图像源。要使其出现在图像元素中,您需要做的就是将src设置为端点URL,如下所示。除非您需要运行一个进程来对图像做些事情,否则不需要获取数据作为数组缓冲区。

document.getElementById("imgsrc").src = "https://www.instagram.com/p/B_zZCRpB895/media/?size=t";
相关问题