一、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;
}