<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<table>
<tr>
<td>
<a href="javascript:;" class="input-file">
<input accept="image/*" name="upimage" id="upload_file" type="file">
</a>
</td>
<td><input type="button" value="Base64編碼" onclick="gen_base64()"/></td>
<td>
<input value="還原生成的Base64編碼爲圖片:" class="tools_btn02" type="button" onclick="test_base64();">
</td>
<td>javascript
</td>
</tr>
</table>
<div id="img_size" style="display:none"></div>
<textarea id="base64_output" name="Word" style="height:200px; width:820px;"></textarea>
<img id="img_prev" src="" style="max-width:100%;border: 1px solid gray;" data-bd-imgshare-binded="1">
</body>
</html>
<script>
function $_(id) {
return document.getElementById(id);
}
function gen_base64() {
$_('base64_output').value = '';
$_('img_size').innerHTML = '';
$_('img_prev').src = '';
var file = $_('upload_file').files[0];
if(!/image\/\w+/.test(file.type)){
alert("請確保文件爲圖像類型");
return false;
}
r = new FileReader(); //本地預覽
r.onload = function(){
$_('base64_output').value = r.result;
$_('img_size').innerHTML = " 圖片大小:" + Math.round(r.result.length/1024*1000)/1000 + " KB";
}
r.readAsDataURL(file); //Base64
alert("編碼成功");
}
function test_base64() {
$_('img_prev').src = '';
$_('img_prev').src = $_('base64_output').value;
}html
</script>java