The input tag of js uploads the image and converts it to base64 for preview

The input tag of js uploads the image and converts it to base64 for preview

background

The file obtained by the input tag belongs to the file type, and if the front end wants to preview the image to be uploaded, it needs to convert the file type to a base64 string

Solution

<input type="file" accept="image/*" @change="beforeUpload">
<img :src="previewUrl" />

beforeUpload(file) {
    
    
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    
    
    console.log('请上传JPG或者PNG格式的图片');
    return false;
  }
  const isLt5M = file.size / 1024 / 1024 < 5;
  if (!isLt5M) {
    
    
    console.log('图片大小限制5M');
    return false;
  }
  
  let reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = (e) => {
    
    
    // 图片base64化
    const base64Str = e.target.result; // 转化后的base64字符串
    this.previewUrl = base64Str; // 预览图片的src路径,赋值为base64字符串
  };
  
  this.fileData = file;
}

Guess you like

Origin blog.csdn.net/Boale_H/article/details/130688291