Vue project, transfer image files to base64 format and display them on the front end as images

Problem Description

The front desk needs to display the picture, and the background is expected to return the picture address directly, but the backstage gives the file stream instead of a picture address, and the file stream needs to be displayed in base64 format.

When requesting the back-end interface, the content of the returned picture is as follows: The picture
Insert picture description here
above is not in base64 format, and the file stream data is twenty binary. If the front-end wants to display, only need to convert the data format to base64.

Solution

  1. Need to add responseType: "arraybuffer" in the interface for getting pictures
  getVerifyCode({
    
    
    tel = '',
  }) {
    
     // 获取图形验证码
    return request({
    
    
      url: 'test/xxx/xxx',
      method: 'post',
      data: Object.assign({
    
    
        username: tel
      }, commonquery()),
      responseType: 'arraybuffer'
    })
  }, 

The interface after setting responseType:'arraybuffer' returns:
Insert picture description here

  1. Add an img tag where you need to display the picture
 <img
            :src="verifyImg"
            @click="getVerify"
          />
  1. Base64 conversion display
    Assignment to verifyImg variable bound to src
 getVerify() {
    
    
      inviteApi["getVerifyCode"]({
    
    
        tel: this.tel
      })
        .then(res => {
    
    
          const src =
            "data:image/png;base64," +
            btoa(
              new Uint8Array(res.data).reduce(
                (data, byte) => data + String.fromCharCode(byte),
                ""
              )
            );
          this.verifyImg = src;
        })
        .catch(error => {
    
    
          console.log(error);
        });
    },
  1. The picture finally displayed on the front-end page is shown in the following figure.
    Insert picture description here
    Reference: The front-end converts the picture file to base64 format and displays it on the front-end, displaying the picture

Guess you like

Origin blog.csdn.net/weixin_45811256/article/details/112575704