<input
id="fileInput"
type="file"
@change="onSelectFileInputChange"
@drag.stop
@dragover.stop
style="display: none;"
:multiple="false" //设为true时可以同时上传多个文件
accept="image/png" //限制上传的文件类型
title=""
/ >
mounted() {
// 防止拖拽时容器奔溃,要阻止拖拽事件的默认行为
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)
},
// 分块读取文件,不然文件太大会读取失败
readFileInChunks(file, callback) {
const chunkSize = 2097152; // 2MB
const fileSize = file.size;
let offset = 0;
const reader = new FileReader();
reader.onload = function (e) {
// 继续读取剩余部分
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
})
})
},
// 更改拖拽时的图标
#fileInput::file-selector-button {
background-image: url('path_to_your_icon.png');
background-size: contain;
background-repeat: no-repeat;
height: 30px; /* 设置按钮的高度 */
width: 100px; /* 设置按钮的宽度 */
border: 1px solid #999; /* 设置按钮的边框 */
color: #333; /* 设置按钮的文本颜色 */
padding: 5px 10px; /* 设置按钮内的填充 */
}
#fileInput {
/* 隐藏默认的文件选择控件 */
position: absolute;
clip: rect(0, 0, 0, 0);
}