var reader = new FileReader();
reader.readAsDataURL(this.files[0]);
reader.onload = function(){
console.log(reader.result); //获取到base64格式图片
};
2.base64转file
function dataURLtoFile(dataurl, filename) {//将base64转换为文件
var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, {type:mime});
}
3. 案例 实现图片的file转bease64,base64转file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="file" name="" id="imgfile">
<img src="" alt="">
<script>
//将file文件转换为base64
document.getElementById('imgfile').onchange = function () {
var fileReader = new FileReader();
fileReader.readAsDataURL(this.files[0]);
fileReader.onload = function () {
var base64 = fileReader.result;
console.log(base64, 'img11')
document.querySelector('img').src = base64
console.log(dataURLtoFile(base64, 'base64转换file'));
}
}
//将base64转换为文件
function dataURLtoFile(dataurl, filename) {
var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, { type: mime });
}
</script>
</body>
</html>
发表评论