日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > HTML >内容正文

HTML

fileReader学习-前端展示本地图片

發布時間:2024/1/8 HTML 42 豆豆
生活随笔 收集整理的這篇文章主要介紹了 fileReader学习-前端展示本地图片 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

最近項目中會使用富文本編輯器,發現源碼中有fileReader,來學習一下~

FileReader的學習

FileReader是一種異步文件讀取機制,結合input:file可以方便的讀取本地文件(圖片/txt)

一、input的file類型

<input type=“file” id = “inputBox”>

在頁面上的顯示是這樣的:

當你點擊選擇文件的按鈕,便可以選擇本地的文件。選擇后的頁面如下所示,文字部分會顯示你選擇的文件名稱。

我們在控制臺試著輸入 inputBox.files 將會看到:

為input標簽加上webkitdirectory屬性,可上傳文件夾

<input type=“file” id = “inputBox” webkitdirectory>

例如:

我們可以看到,雖然file對象獲取到了文件的描述信息,但沒有辦法獲取到文件的數據。需要通過html5提供的FileReader讀取文件中的數據。

fileReader

1.實例的創建 var reader = new FileReader();
2.FileReader的方法:
常用的兩個方法在上圖中圈出。我們來測試一下~
(1)readAsDataURL(file)

<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Title</title><style>img{width:200px;}</style> </head> <body> <input type="file" name="" id="inputBox"> <br/> <img src="" id="img"> <span id="span"></span> <script language="javascript">//讀取圖片類型var inputBox = document.getElementById("inputBox");inputBox.addEventListener("change",function(){var reader = new FileReader();reader.readAsDataURL(inputBox.files[0]);//發起異步請求reader.onload = function(){img.src = this.result//讀取完成后,數據保存在對象的result屬性中console.log(this.result)}}) </script>

我們先看一下控制臺打印出來的result是怎么樣的

輸出的是文件的base64編碼
將這個結果賦給img.src,即可在頁面中展示出本地圖片了,效果如下

(2)readAsText(file,encoding)
其中,encoding的默認值為“UTF-8”。這個用法與上例類似

//讀取txt類型var inputBox = document.getElementById("inputBox");inputBox.addEventListener("change",function(){var reader = new FileReader();reader.readAsText(inputBox.files[0]);//發起異步請求reader.onload = function(){var span = document.getElementById("span")span.append(this.result);//讀取完成后,數據保存在對象的result屬性中console.log(this.result)}})


3.FileReader的事件

var inputBox = document.getElementById("inputBox");var count=0;inputBox.addEventListener("change",function(){var reader = new FileReader();reader.readAsText(inputBox.files[0],"utf-8");//發起異步請求reader.onload = function(){console.log("加載成功")}reader.onloadstart = function(){console.log("開始加載")}reader.onloadend= function(){console.log("加載結束")}reader.onprogress = function(){count++;console.log("加載中"+count)}})

我們來讀取一下一個比較大的文件 來看一下加載過程是怎么樣的~

我們可以看到,事件的順序為 onloadstart–>onprogress(周期性執行)–>onload–>onloadend(無論成功還是失敗,都回調用)

總結

以上是生活随笔為你收集整理的fileReader学习-前端展示本地图片的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。