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


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

    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接收在转换成对应格式的图片或文件

  • 相关阅读:
    SpringBoot集成Shardingjdbc+seata AT模式
    【Stream】
    【副业合集】60个正规可做兼职的网站
    NAT网络地址转换技术
    反素数
    机器学习模型,超级全面总结!
    【Redis】.net core Redis事件订阅与发布,基础篇
    nginx进程间同步机制-互斥锁
    day24每日一考
    善网ESG周报(第一期)
  • 原文地址:https://blog.csdn.net/tjj3027/article/details/132696284