需求:通過頁面的按鈕實(shí)現(xiàn)本地文件的選擇(以選擇歌曲為例)。
思路:利用原生input的type="file"來實(shí)現(xiàn)。
###1.先自定義上傳按鈕
//HTML部分
<div class="p10 bs mb10" style="height: 40px">
<el-button type="text" size="small" @click="triggerFileInput">
選擇歌曲
</el-button>
<span class="f12 ml10">請(qǐng)先選擇本地音樂?。。?lt;/span>
<input
ref="audioInput"
style="display: none; height: 10px"
type="file"
@change="handleFileSelect"
multiple
accept="audio/*"
/>
</div>
//input的點(diǎn)擊事件轉(zhuǎn)移到自定義的按鈕上面
triggerFileInput() {
this.$refs.audioInput.click();
},
2.獲取上傳數(shù)據(jù)<通過input的change事件可實(shí)現(xiàn)>
// 添加本地音樂
handleFileSelect(event) {
const files = event.target.files;
this.selectedFiles = JSON.parse(JSON.stringify(musicList));
this.fileUrl = null;
for (let i = 0; i < files?.length; i++) {
const file = files[i];
const reader = new FileReader();
reader.onload = (e) => {
const fileObj = {
name: file.name,
url: e.target.result,
// lrc: null,
lrcList: [],
};
this.selectedFiles.push(fileObj);
};
reader.readAsDataURL(file);
}
},
這里將選擇的歌曲處理格式之后存放進(jìn)selectedFiles的數(shù)組,以便后續(xù)操作。