<!Doctype html>
<
html
>
<
head
>
<
meta
charset
=
"utf-8"
/>
<
title
>html5 图片转base64编码</
title
>
<
style
>
* {
margin: 0;
padding: 0;
}
.demo{
width: 100%;
margin: 50px;
}
</
style
>
<
script
type
=
"text/javascript"
>
window.onload = function() {
// 抓取上传图片,转换代码结果,显示图片的dom
var img_upload = document.getElementById("img_upload");
var base64_code = document.getElementById("base64_code");
var img_area = document.getElementById("img_area");
// 添加功能出发监听事件
img_upload.addEventListener('change', readFile, false);
}
function readFile() {
var file = this.files[0];//这里是抓取到上传的对象。
if(!/image\/\w+/.test(file.type)) {
alert("请确保文件为图像类型");
return false;
}
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function() {
base64_code.innerHTML = this.result;
//this.result里的这个result是FileReader.readAsDataURL()接口当中转换完图片输出的base64结果存放在result当中
img_area.innerHTML = '<
div
>图片img标签展示:</
div
><
img
src
=
"' + this.result + '"
alt
=
""
/>';
}
}
</
script
>
</
head
>
<
body
>
<
div
class
=
"demo"
>
<
input
type
=
"file"
id
=
"img_upload"
/>
<
textarea
id
=
"base64_code"
rows
=
"30"
cols
=
"100"
></
textarea
>
<
p
id
=
"img_area"
></
p
>
</
div
>
</
body
>
</
html
>