js 图片转base64方式
发布日期:2023-02-27 13:46:11
<!DOCTYPE html><html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>js 图片转base64方式</title>
</head>
<body>
BASE64图片: <input type="file" id="image"><br/>
<button id="up">上传</button>
<img id="imgUp">
<script src="https://apps.bdimg.com/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$("#up").click(function(){
var reader = new FileReader();
var AllowImgFileSize = 2100000; //上传图片最大值(单位字节)( 2 M = 2097152 B )超过2M上传失败
var file = $("#image")[0].files[0];
var imgUrlBase64;
if (file) {
//将文件以Data URL形式读入页面
imgUrlBase64 = reader.readAsDataURL(file);
reader.onload = function (e) {
//var ImgFileSize = reader.result.substring(reader.result.indexOf(",") + 1).length;//截取base64码部分(可选可不选,需要与后台沟通)
if (AllowImgFileSize != 0 && AllowImgFileSize < reader.result.length) {
alert( '上传失败,请上传不大于2M的图片!');
return;
}else{
//执行上传操作
//alert(reader.result);
$("#imgUp").attr("src",reader.result);
}
}
}
});
</script>
</body>
</html>