Front-end JS displays uploaded image thumbnails (local image read)

Requirement: Click the upload image button, after selecting the image, the image will be displayed directly in the thumbnail without requesting the backend interface.

Solution: Use the methods in FileReaderand .FileReaderreadAsDataURL

The first step
is to get the data from input[type=“file”](upload file tag) file, similar to the picture below .
insert image description here
The second step
is to get the file data, execute the following code

// file 是文件数据

// 读取文件
var reader = new FileReader();
// base64位读取
reader.readAsDataURL(file);
reader.onload = function (e) {
    
    
  // 给img标签src复制(结果是base64图片)
  img_src = e.target.result;
}

Show results:


insert image description here
Select picture before selection
insert image description here
After selection
insert image description here

Guess you like

Origin blog.csdn.net/qq_17627195/article/details/131942610