• [交互]前端展示服务端获取的图片


    可以通过以下步骤从服务端获取图片:

    1. 引入axios库:在前端代码中使用axios库来发送HTTP请求。可以通过以下方式引入axios:

      import axios from 'axios';
      
      • 1
    2. 发送请求:使用axios发送HTTP请求,获取图片文件的二进制数据。发送请求的代码示例:

      axios({
        method: 'GET',
        url: 'http://your-domain.com/path/to/image.jpg',
        responseType: 'arraybuffer'
      }).then(response => {
        // 将响应的二进制数据转换为Blob对象
        const blob = new Blob([response.data], { type: response.headers['content-type'] });
        // 根据Blob对象生成图片URL
        const imgUrl = URL.createObjectURL(blob);
        // 将图片URL赋值给图片元素的src属性
        const imgElement = document.querySelector('#my-img');
        imgElement.src = imgUrl;
      });
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13

      在上面的代码中,responseType设置为arraybuffer,表示响应的数据以二进制数组的形式返回。在响应成功的回调函数中,将响应的二进制数据转换为Blob对象,并根据Blob对象生成图片URL,最后将图片URL赋值给图片元素的src属性,即可显示图片。


      axios({
        method: 'GET',
        url: 'http://your-domain.com/path/to/getImage',
        responseType: 'blob'
      }).then(response => {
        // 将响应的二进制数据转换为Blob对象
        const blob = new Blob([response.data], { type: response.headers['content-type'] });
        // 根据Blob对象生成图片URL 将图片URL赋值给图片元素的src属性
       const reader = new FileReader();
       reader.readAsDataURL(blob);
       reader.onload = function (e) {
         imgUrl = e.target.result;// e.target.result 即为base64结果
       };
       reader.onerror = (error) => {
         console.log("图形加载错误");
       };
    
    
      });
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    在上面的代码中,responseType设置为blob,表示响应的数据以blob对象的形式返回。在响应成功的回调函数中,将响应的二进制数据转换为Blob对象,并根据Blob对象生成图片URL,最后将图片URL赋值给图片元素的src属性,即可显示图片。

    以上虽然设置了blob但是根本上还是图片以二进制的形式传输的,因为所有非json格式,均可以以blob接收在转换成对应格式的图片或文件

  • 相关阅读:
    java的集合
    clickhouse介绍
    VMware vCenter Server 6.7 安装
    【软件STM32cubeIDE下H73xx配置串口uart1+中断接收/DMA收发+HAL库+简单数据解析-基础样例】
    Socket网络编程练习题四:客户端上传文件(多线程版)
    nvm的简介、安装、使用(简单明了)
    iOS学习 --- Xcode 15 下载iOS_17.0.1_Simulator失败解决方法
    C/C++浮点数向零舍入 2019年9月电子学会青少年软件编程(C/C++)等级考试一级真题答案解析
    JWT
    JavaScript学习Day003(内置对象)
  • 原文地址:https://blog.csdn.net/tjj3027/article/details/132696284