相關(guān)API
1.文件拖拽事件
- ondragover -> 只要懸浮,一直觸發(fā)
- ondragenter -> 進(jìn)入時(shí)觸發(fā),有子節(jié)點(diǎn)時(shí)有問題
- ondragleave -> 離開時(shí)觸發(fā),有子節(jié)點(diǎn)時(shí)有問題
- ondrop -> 釋放鼠標(biāo)時(shí)觸發(fā),對應(yīng)DOM節(jié)點(diǎn)的dragover事件必須取消默認(rèn)事件
2.File接口
- var reader = new FileReader(); 新建文件讀取對象
調(diào)用對象方法 - .readAsText(file) -> 讀取文本文件
- .readAsDataURL(file) -> 將文件讀取為 DataURL(二進(jìn)制流形式)
- .readAsBinaryString -> 將文件讀取為 二進(jìn)制編碼
3.處理事件
- .onload -> 資源讀取完畢 reader.result
- .onprogress -> 讀取進(jìn)度更新時(shí)觸發(fā)
- .onloadstart -> 加載開始時(shí)觸發(fā)
- .onloadend -> 加載結(jié)束時(shí)觸發(fā)
- .onerror -> 出現(xiàn)錯(cuò)誤時(shí)觸發(fā)
- .onabort -> 加載過程中中止時(shí)觸發(fā)
- .abort -> 手動(dòng)中止加載
代碼實(shí)現(xiàn)
HTML部分
<input type="file" id="input_file"/>
<div id="result" style="width: 100px;height: 100px;border: 1px solid #E1E1E1;"></div>
<div id="box" style="width: 400px;height: 100px;border: 1px solid #E1E1E1;"></div>
Javascript
var input=document.getElementById("input_file");
var result=document.getElementById("result");
if (window.FileReader) {
input.addEventListener("change",imageUpload,false);
} else{
alert("瀏覽器不支持fileReader")
}
//普通上傳圖片
function imageUpload () {
var file = this.files[0];
var reader = new FileReader();
if(!/image\/\w+/.test(file.type)){
alert("請確保文件為圖像類型");
return false;
}
reader.readAsDataURL(file);
reader.onload = function(ev) {
console.log(this.result);//二進(jìn)制流
result.innerHTML=''
}
}
//拖拽上傳圖片或處理文本或者多媒體(圖片 音頻 視頻)
var oBox=document.getElementById("box");
oBox.ondrop=function () {
var file = this.files[0];
var reader = new FileReader();
if (/txt/.test(file.type)) {
reader.readAsText(file);
reader.onload = function(ev) {
console.log(this.result);
document.write(this.result)
}
} else{
reader.readAsDataURL(file);
if (/iamge/.test(file.type)) {
reader.onload = function(ev) {
console.log("image");
var oImg=new Image();
oImg.src=this.result;
document.body.appendChild(oImg);
}
}
if (/video/.test(file.type)) {
reader.onload = function(ev) {
console.log("video");
new Video(this.result).play();
}
}
if (/audio/.test(file.type)) {
reader.onload = function(ev) {
console.log("audio")
new Audio(this.result).play();
}
}
}
}
以上為HTML5 fileReader用法,內(nèi)容不多理解較為容易,不再贅述。