读取本地文件理解FileReader对象的方法和事件以及上传按钮的美化。

一、FileReader对象

用来把文件读入内存,并且读取文件中的数据。FileReader对象提供了异步API,使用该API可以在浏览器主线程中异步访问文件系统,读取文件中的数据。

浏览器支持情况,可以根据window.FileReader进行判断,火狐、谷歌支持,IE不支持。

二、FileReader的方法和事件介绍

表一:方法;表二:事件;

readAsBinaryString(file)

将文件读取二进制码;
通常我们将它传送到后端,后端可以通过这段字符串存储文件;

readAsText(file, [encoding]) 将文件读取为文本;
该方法有两个参数,其中第二个参数是文本的编码方式,默认值为 UTF-8。这个方法非常容易理解,将文件以文本方式读取,读取的结果即是这个文本文件中的内容。
readAsDataURL(file) 将文件读取为DataURL;
将文件读取为一串Data URL字符串,将小文件以一种特殊格式的URL地址直接读入页面。小文件指图像与html等格式的文件。
abort 中断读取

 

 

 

 

 

 

onabort 数据读取中断时触发
onerror 数据读取出错时触发
onloadstart 数据读取开始时触发
onload 数据读取成功完成时触发
onloadend 数据读取完成时触发,无论成功失败

 

 

 

 


 

code:

<body>
<img id="image"src=""/>
<input type="file" onchange="selectImage(this);"/>
<script>
if(window.FileReader){
  function selectImage(file){
    var reader = new FileReader();
    reader.readAsDataURL(file.files[0]);
    reader.onload = function(evt){
      document.getElementById('image').src = evt.target.result;
    }
  }
}else{
  console.log('浏览器不支持FileReader');
}
</script>
</body>

FileReader对象的这几个方法用法是一样的。

三、input type="file" 上传按钮美化

input file上传按钮的美化思路是,先把之前的按钮透明度opacity设置为0,然后,外层用div或a包裹,就实现了美化功能。

html:

<a href="javascript:;" class="a-upload">
<input type="file" name="" id="">上传按钮1
</a>
<a href="javascript:;" class="file">上传按钮2
<input type="file" name="" id="">
</a>

css:

第一个按钮:

.a-upload {
padding: 4px 10px;
height: 20px;
line-height: 20px;
position: relative;
cursor: pointer;
color: #888;
background: #fafafa;
border: 1px solid #ddd;
border-radius: 4px;
overflow: hidden;
display: inline-block;
*display: inline;
*zoom: 1
}

.a-upload input {
position: absolute;
font-size: 100px;
right: 0;
top: 0;
opacity: 0;
filter: alpha(opacity=0);
cursor: pointer
}

.a-upload:hover {
color: #444;
background: #eee;
border-color: #ccc;
text-decoration: none
}

第二个按钮:

.file {
position: relative;
display: inline-block;
background: #D0EEFF;
border: 1px solid #99D3F5;
border-radius: 4px;
padding: 4px 12px;
overflow: hidden;
color: #1E88C7;
text-decoration: none;
text-indent: 0;
line-height: 20px;
}
.file input {
position: absolute;
font-size: 100px;
right: 0;
top: 0;
opacity: 0;
}
.file:hover {
background: #AADFFD;
border-color: #78C3F3;
color: #004974;
text-decoration: none;
}

posted @ 2015-12-17 17:05  五谷道场  阅读(4924)  评论(1编辑  收藏  举报