核心:
function file2base64(){
fileAddress = document.getElementById("fileImage").files[0];
file = new FileReader();
file.readAsDataURL(fileAddress);
file.onload = function(){console.log(file.result);}
}
完整代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="file" name="" id="fileImage">
<button onclick="file2base64()">文件转base64</button>
<script>
function file2base64(){
fileAddress = document.getElementById("fileImage").files[0];
file = new FileReader();
file.readAsDataURL(fileAddress);
file.onload = function(){console.log(file.result);}
}
</script>
</body>
</html>
![]()