首页 > 解决方案 > 将axios返回的图片转换成vue可以显示的东西

问题描述

我向堆栈溢出社区寻求帮助。基本上整个情况的多头和空头会显示在下面:

  1. 在 Vue 页面上,我正在使用下面显示的代码向 Nodejs 服务器发出请求
  2. 该 node.js 服务器正在连接到 Linux 设备并从中提取图像
  3. 该 node.js 服务器然后将此图像返回到上述 Vue 页面
await axiosT({
            
    method: 'post',
    url: '{this is removed for security reasons}',
    data: {this is removed for security reasons},
    headers: {'Content-Type': 'application/x-www-form-urlencoded' },
    responseType: 'text',

}).then(function (response) {
                    
   console.log(response.data);

}

这执行没有错误,我已经在邮递员中完成了这个响应工作,它成功地显示了检索到的图像。在收到图像和控制台记录它。我遇到了下面显示的一堆废话,我只能假设这是一种或另一种形式的图像;但是,正如现在我所做的以任何方式显示图像的所有尝试一样,在最坏的情况下,没有使用零错误消息,或者充其量只是导致显示丢失的图像图标

������JFIF�����`�`�����<CREATOR: gd-jpeg v1.0 (using IJG JPEG v80), quality = 100
���C��������������������������������������������������������������������C������������������������������������������������������������������������������������������������������������������ 
���������������������}��������!1A��Qa�"q�2����#B���R��$3br� 
�����%&'()*456789:CDEFGHIJST ... and so on and so on, etc etc you get the point

我愿意接受任何建议,如果您需要进一步澄清某些事情,请不要害怕问

标签: javascriptnode.jsimagevue.jsaxios

解决方案


感谢所有的评论,你们都能够帮助我解决它

下面是工作代码,将响应类型更改为 arraybuffer 并添加在 .then() 中找到的代码成功地将图像转换为 base64,它可以设置一个绑定到 my <img>src 的变量(如下所示)。

let image = null;

await axiosT({
                    
    method: 'post',
    url: '{this is removed for security reasons}',
    data: {this is removed for security reasons},
    headers: {'Content-Type': 'application/x-www-form-urlencoded' },
    responseType: 'arraybuffer',
                    
}).then(function (response) {

    try {

        image = ('data:image/jpeg;base64,' + btoa(
           new Uint8Array(response.data).reduce((data, byte) => data + 
           String.fromCharCode(byte), '')
        ));

    } catch (err) {

        console.log(err)

    }
                        
})

this.foo_image = image
<img :src="foo_image">

推荐阅读