<input type="file" id="input" value="" />
<script type="text/javascript">
var fileInput = document.getElementById('input');
fileInput.addEventListener('change', function(event) {
var file = fileInput.files[0];
if (file) {
var reader = new FileReader();
reader.onload = function() {
//处理 android 4.1 兼容问题
var base64 = reader.result.split(',')[1];
var dataUrl = 'data:image/png;base64,' + base64;
console.log("dataUrl:"+dataUrl);
}
reader.readAsDataURL(file);
}
}, false);
</script>
上传文件可以参考一下这个介绍:https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications#Example_Uploading_a_user-selected_file
文件上传代码参考:
fileInput.addEventListener('change', function(event) {
var file = fileInput.files[0];
if (file) {
var reader = new FileReader();
var xhr = new plus.net.XMLHttpRequest();
xhr.onprogress=function(e){
var percentage = Math.round((e.loaded * 100) / e.total);
console.log("percentage:"+percentage);
}
xhr.onload=function(e){
console.log("percentage:100");
}
xhr.open("POST", "这里填写服务器地址");
reader.onload = function(evt) {
xhr.send(evt.target.result);
};
reader.readAsBinaryString(file);
}
});
html5前端图片上传预览效果
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>html5前端图片上传预览效果</title>
<style>
body{margin: 0;}
.fixed{
width: 100%;
height: 100%;
position: fixed;
top:0;
left: 0;
}
.file{
display:block;
height: 120px;
width: 120px;
margin: 0 auto;
position: relative;
top: calc(50% - 60px);
overflow: hidden;
text-decoration: none;
text-indent: 0;
border:none;
}
.file input{
height: 120px;
width: 120px;
font-size: 100px;
margin: 0;
padding: 0;
position: absolute;
right: 0;
top: 0;
opacity: 0;
z-index: 999;
}
.file img{
width: 120px;
height: 120px;
position: absolute;
left: 0;
top: 0;
border: none;
}
</style>
</head>
<body>
<div class="fixed">
<a href="javascript:;" class="file" id="localImag">
<input type="file" id="file"/>
<img src="images/tu.png" id="preImg">
</a>
</div>
<script type="text/javascript">
(function(){
//获取页面的input标签和接受展示的图片标签
var file = document.getElementById("file");
var preImg = document.getElementById("preImg");
// !window.FileReader&&return false;
//给input绑定change事件
file.onchange = function() {
if(window.FileReader){
//创建FileReader对象
var reader = new FileReader();
//接受files数组中的第一个参数
var _file = this.files[0];
//将文件格式转换
reader.readAsDataURL(_file);
//读取完毕后设置图片展示
reader.onload = function() {
preImg.setAttribute('src', this.result);
}
}else{
alert("当前浏览器不支持FileReader,请更新浏览器!");
}
}
})()
</script>
</body>
</html>
