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 FileReader
and .FileReader
readAsDataURL
The first step
is to get the data from input[type=“file”]
(upload file tag) file
, similar to the picture below .
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:
Select picture before selection
After selection