js文件上傳

1、FileReader對象javascript

用來把文件讀入內存,而且讀取文件中的數據。FileReader對象提供了異步API,使用該API能夠在瀏覽器主線程中異步訪問文件系統,讀取文件中的數據。css

瀏覽器支持狀況,能夠根據window.FileReader進行判斷,火狐、谷歌支持,IE不支持。html

2、FileReader的方法和事件介紹java

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

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>this

FileReader對象的這幾個方法用法是同樣的。編碼

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

相關文章
相關標籤/搜索