vue實現(xiàn)文件上傳讀取及下載功能
本文實例為大家分享了vue實現(xiàn)文件上傳讀取及下載的具體代碼,供大家參考,具體內(nèi)容如下
文件的上傳利用input標(biāo)簽的type="file"屬性,讀取用FileReader對象,下載通過創(chuàng)建a標(biāo)簽實現(xiàn)
<template>
<div class="filediv">
<el-button @click="downloadFile">下載</el-button>
<div id="fileselect">
<el-input style="margin-top: 16px" type="file"></el-input>
</div>
</div>
</template>
<script>
export default {
data () {
return {
}
},
mounted: function () {
this.$nextTick(function () {
this.readFile()
})
},
methods: {
// 下載文件
downloadFile: function () {
var content = [
{ 'firstName': 'John', 'lastName': 'Doe' },
{ 'firstName': 'Anna', 'lastName': 'Smith' },
{ 'firstName': 'Peter', 'lastName': 'Jones' }
]
var filecontent = JSON.stringify(content)
if ('download' in document.createElement('a')) {
this.download(filecontent, 'testfile.json')
} else {
alert('瀏覽器不支持')
}
},
// 下載設(shè)備配置文件
download: function (content, filename) {
let link = document.createElement('a')
link.download = filename
link.style.display = 'none'
// 字符內(nèi)容轉(zhuǎn)變成blob地址
let blob = new Blob([content])
link.href = URL.createObjectURL(blob)
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
},
// 導(dǎo)入設(shè)備,監(jiān)聽上傳文件并讀取
readFile: function () {
console.log('讀取文件')
let fileselect = document.querySelector('#fileselect')
fileselect.addEventListener('change', function (e) {
console.log(e)
let file = e.target.files
console.log('文件類型')
console.log(file)
if (file.length === 0) {
return
}
let reader = new FileReader()
if (typeof FileReader === 'undefined') {
this.$message({
type: 'info',
message: '您的瀏覽器不支持FileReader接口'
})
return
}
reader.readAsText(file[0])
reader.onload = function (e) {
console.log('文件內(nèi)容')
console.log(e.target.result)
}
}.bind(this))
}
}
}
</script>
<style scoped>
.filediv {
width: 400px;
margin: 20px;
}
</style>
關(guān)于vue.js的學(xué)習(xí)教程,請大家點擊專題vue.js組件學(xué)習(xí)教程、Vue.js前端組件學(xué)習(xí)教程進行學(xué)習(xí)。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
解決antd Form 表單校驗方法無響應(yīng)的問題
這篇文章主要介紹了解決antd Form 表單校驗方法無響應(yīng)的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-10-10
Vue實現(xiàn)預(yù)覽文件(Word/Excel/PDF)功能的示例代碼
這篇文章主要為大家詳細(xì)介紹了如何通過Vue實現(xiàn)預(yù)覽文件(Word/Excel/PDF)的功能,文中的實現(xiàn)步驟講解詳細(xì),需要的小伙伴可以參考一下2023-03-03
vite+vue3中使用mock模擬數(shù)據(jù)問題
這篇文章主要介紹了vite+vue3中使用mock模擬數(shù)據(jù)問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-03-03
vue 中this.$set 動態(tài)綁定數(shù)據(jù)的案例講解
這篇文章主要介紹了vue 中this.$set 動態(tài)綁定數(shù)據(jù)的案例講解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-01-01
關(guān)于vxe-table復(fù)選框翻頁選中問題及解決
這篇文章主要介紹了關(guān)于vxe-table復(fù)選框翻頁選中問題及解決,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-09-09

