上传图片直接预览(blob 和 new FileReader() 转换base64)

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<input type="file" onchange="onchange">
<div></div>
<img src="" id='imgf' alt="">
<div></div>
<canvas id="canvas"></canvas>
<script>
let geturl = function(file) {
let url = null;
url = window.webkitURL.createObjectURL(file) //没做兼容性
var ctx = canvas.getContext('2d');
var img = new Image();
img.onload = function() {
ctx.drawImage(img, 0, 0, 500, 500)
}
img.src = url
// imgf.src=url 直接blob图片
}
var canvas = document.getElementById('canvas');
var imgf = document.getElementById('imgf');
canvas.height = 500;
canvas.width = 500;
var onchange = function(e) {
let file = (e.target.files[0])
geturl(file)
// const reader = new FileReader() 转换base64
// reader.onload = function () {
// console.log(reader.result)
// }
// reader.readAsDataURL(file)
}
</script>
</body>
</html>

posted @ 2023-03-14 11:14  mrt_yy  阅读(26)  评论(0编辑  收藏  举报