vue可以操作本地文件,其操作方法是:1、利用“XMLHttpRequest”對(duì)本地文件進(jìn)行讀取操作;2、利用“input”標(biāo)簽上傳文件,然后使用“FileReader”對(duì)象和異步api,讀取文件中的數(shù)據(jù)。
本教程操作環(huán)境:Windows10系統(tǒng)、Vue 3版、Dell G3電腦。
vue可以操作本地文件嗎?
可以。
Vue項(xiàng)目通過(guò)讀取本地文件內(nèi)容來(lái)顯示內(nèi)容
需求:
公司項(xiàng)目需要在登陸之前,實(shí)現(xiàn)客戶自定義項(xiàng)目標(biāo)題。由于還未登陸,所以肯定無(wú)法通過(guò)后端管理系統(tǒng)配置。
第一個(gè)想到的辦法是通過(guò)讀取本地文件內(nèi)容,來(lái)顯示標(biāo)題內(nèi)容。
客戶需要求改標(biāo)題時(shí),直接修改本地文件內(nèi)容即可。
實(shí)現(xiàn)
讀取本地文件的思路有兩種,第一種是利用XMLHttpRequest,第二種是利用input的type=file將文件先上傳,再讀取。
第一種:
利用XMLHttpRequest對(duì)本地文件進(jìn)行讀取操作,值得注意的是,HTML文檔的格式要與流中的讀取格式設(shè)置一致, 代碼如下:
methods: { readFile(filePath) { // 創(chuàng)建一個(gè)新的xhr對(duì)象 let xhr = null if (window.XMLHttpRequest) { xhr = new XMLHttpRequest() } else { // eslint-disable-next-line xhr = new ActiveXObject('Microsoft.XMLHTTP') } const okStatus = document.location.protocol === 'file' ? 0 : 200 xhr.open('GET', filePath, false) xhr.overrideMimeType('text/html;charset=utf-8') xhr.send(null) return xhr.status === okStatus ? xhr.responseText : null },}
首先創(chuàng)建一個(gè)讀取文件內(nèi)容的函數(shù)readFile,通過(guò)XMLHttpRequest對(duì)象,讀取指定路徑中的文件,格式指定為text/html,并返回內(nèi)容。
然后直接在login組件的created鉤子函數(shù)中,調(diào)用并讀取文件內(nèi)容,賦值給需要顯示的標(biāo)題title屬性。
created() { this.getList() this.title = this.readFile('../../../static/title.txt') console.log(this.title) },
本次項(xiàng)目需求就是使用此方案解決。
第二種:
上傳文件利用input標(biāo)簽,然后使用FileReader對(duì)象,h5提供的異步api,可以讀取文件中的數(shù)據(jù)。
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>Document</title> </head> <body> <span>點(diǎn)擊上傳:</span> <input type="file" id="files1" onchange="uploadFile1()"> <br> <span>點(diǎn)擊上傳2:</span> <input type="file" id="files2" onchange="uploadFile2(event)"> <script> function uploadFile1() { const selectedFile = document.getElementById('files1').files[0] // 讀取文件名 const name = selectedFile.name // 讀取文件大小 const size = selectedFile.size // FileReader對(duì)象,h5提供的異步api,可以讀取文件中的數(shù)據(jù)。 const reader = new FileReader() // readAsText是個(gè)異步操作,只有等到onload時(shí)才能顯示數(shù)據(jù)。 reader.readAsText(selectedFile) reader.onload = function () { //當(dāng)讀取完成后回調(diào)這個(gè)函數(shù),然后此時(shí)文件的內(nèi)容存儲(chǔ)到了result中,直接操作即可 console.log(this.result); } } function uploadFile2(e) { const selectedFile = e.target.files[0] const reader = new FileReader() // 文件內(nèi)容載入完畢之后的回調(diào)。 reader.onload = function(e) { console.log(e.target.result) } reader.readAsText(selectedFile) } </script> </body></html>
推薦學(xué)習(xí):《vue視頻教程》