h5利用file將圖片轉為base64
阿新 • • 發佈:2019-02-20
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
.upload_img{
width:300px;
height: 300px;
margin: 100px auto;
background-color: lightskyblue;
text-align: center;
line-height: 300px;
font-size: 16px;
}
</style>
</head>
<body>
<div class="upload_img">
上傳
</div>
<img src=""/>
</body>
</html>
<script type="text/javascript">
window.onload = function(){
var uploadImg = document.querySelector(".upload_img");
var oImg = document.getElementsByTagName("img")[0]
uploadImg.onclick = function(ev){
var oInput = document.createElement("input");
oInput.type = "file";
oInput.click();
oInput.addEventListener("change",function(){
var oFile = this.files[0];
if(!/image\/\w+/.test(oFile.type)){
alert("請確保檔案為影象型別");
return false;
}
var render = new FileReader();
render.readAsDataURL(oFile);
render.onload = function(e){
var result = this.result
oImg.src = result;
}
});
}
}
</script>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
.upload_img{
width:300px;
height: 300px;
margin: 100px auto;
background-color: lightskyblue;
text-align: center;
line-height: 300px;
font-size: 16px;
}
</style>
</head>
<body>
<div class="upload_img">
上傳
</div>
<img src=""/>
</body>
</html>
<script type="text/javascript">
window.onload = function(){
var uploadImg = document.querySelector(".upload_img");
var oImg = document.getElementsByTagName("img")[0]
uploadImg.onclick = function(ev){
var oInput = document.createElement("input");
oInput.type = "file";
oInput.click();
oInput.addEventListener("change",function(){
var oFile = this.files[0];
if(!/image\/\w+/.test(oFile.type)){
alert("請確保檔案為影象型別");
return false;
}
var render = new FileReader();
render.readAsDataURL(oFile);
render.onload = function(e){
var result = this.result
oImg.src = result;
}
});
}
}
</script>