<input
id="fileInput"
type="file"
@change="onSelectFileInputChange"
@drag.stop
@dragover.stop
style="display: none;"
:multiple="false" //設(shè)為true時(shí)可以同時(shí)上傳多個(gè)文件
accept="image/png" //限制上傳的文件類型
title=""
/ >
mounted() {
// 防止拖拽時(shí)容器奔潰,要阻止拖拽事件的默認(rèn)行為
const dragArr = ['dragenter', 'dragover', 'drop']
dragArr.forEach((name) => {
document.addEventListener(name, (event) => {
event.preventDefault()
})
this.$once('hook:beforeDestroy', () => {
document.removeEventListener(name, (event) => {
event.preventDefault()
})
})
})
},
// 拖拽更新文檔
onSelectFileInputChange(e) {
const files = e?.target?.files
if (!files.length) {
return
}
const file = files[0]
const path = e?.target
this.getFileInfo(file)
},
// 分塊讀取文件,不然文件太大會(huì)讀取失敗
readFileInChunks(file, callback) {
const chunkSize = 2097152; // 2MB
const fileSize = file.size;
let offset = 0;
const reader = new FileReader();
reader.onload = function (e) {
// 繼續(xù)讀取剩余部分
offset += chunkSize;
if (offset < fileSize) {
reader.readAsDataURL(file.slice(offset, offset + chunkSize));
} else {
callback({ data: reader, error: false })
}
};
reader.onerror = function () {
callback({ data: null, error: true })
};
// 開始讀取第一塊
reader.readAsDataURL(file.slice(offset, offset + chunkSize));
},
//獲取文件信息
getFileInfo(file) {
return new Promise(async (resolve) => {
if (!file || !file.size || !file.name) {
resolve(null)
return
}
this.readFileInChunks(file, (result) => {
if (result.error) {
return
}
//獲取到文件的base64
const content = result.data.result
})
})
},
// 更改拖拽時(shí)的圖標(biāo)
#fileInput::file-selector-button {
background-image: url('path_to_your_icon.png');
background-size: contain;
background-repeat: no-repeat;
height: 30px; /* 設(shè)置按鈕的高度 */
width: 100px; /* 設(shè)置按鈕的寬度 */
border: 1px solid #999; /* 設(shè)置按鈕的邊框 */
color: #333; /* 設(shè)置按鈕的文本顏色 */
padding: 5px 10px; /* 設(shè)置按鈕內(nèi)的填充 */
}
#fileInput {
/* 隱藏默認(rèn)的文件選擇控件 */
position: absolute;
clip: rect(0, 0, 0, 0);
}