Scene: Get to a file type of picture, if the preview directly in html? Here is the use of the new features of html5, convert the picture is displayed in the form of Base64. There are two ways:
Method 1: Use URL.createObjectURL ()
<!DOCTYPE html>
<html>
<head>
<title>base</title>
</head>
<body>
<input type="file" name="" id="file">
<img src="" id="img">
<script type="text/javascript">
window.onload = function () {
let $img = document.getElementById('img')
file.onchange = function (e) {
console.log(e.target.files[0])
let file = e.target.files[0]
let fileUrl = window.URL.createObjectURL(file)
$img.src = fileUrl
img.onload = function () {
// 手动回收
URL.revokeObjectURL(fileUrl)
}
}
}
</script>
</body>
</html>
When you select the picture, resulting img src Similarly "blob:null/4304d4f3-c13b-43e8-83f6-8c80426520ff"
, the normal display picture.
Method two: use FileReader.readAsDataURL ()
<!DOCTYPE html>
<html>
<head>
<title>base</title>
</head>
<body>
<input type="file" name="" id="file">
<img src="" id="img">
<script type="text/javascript">
window.onload = function () {
let $img = document.getElementById('img')
file.onchange = function (e) {
console.log(e.target.files[0])
let file = e.target.files[0]
const fr = new FileReader(file)
fr.readAsDataURL(file)
fr.onload = function () {
$img.src = this.result
}
}
}
</script>
</body>
</html>
src img tag would be like this: "data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAABkCAYAAADDhn8LAAA==
can display properly.
Original link: https://juejin.im/post/5b5187da51882519ec07fa41