【论术】原生文件夹上传
君不见,高堂明镜悲白发,朝如青丝暮成雪 ——李白 · 《将进酒》
项目需求:支持目录上传,由于历史原因无法使用组件库,索性用原生写了一个:
// `上传目录按钮`
handleAddFolder() {
const _this = this;
const input = document.createElement("input");
input["style"] =
"background: rgba(255, 255, 255, 0);overflow: hidden;position: fixed;width: 1px;height: 1px;z-index: -1;opacity: 0;";
input.type = "file";
input.setAttribute("allowdirs", "true");
input.setAttribute("directory", "true");
input.setAttribute("webkitdirectory", "true");
input.multiple = true;
document.querySelector("body").appendChild(input);
input.click();
input.onchange = async function (e) {
console.log('e.target["files"] :>> ', e.target["files"]);
const formData = new FormData();
const file = e.target["files"];
console.log("file :>> ", file);
// 文件数组,如果最终为空则取消本次上传动作
let fileList = [];
for (let i = 0; i < file.length; i++) {
// 判断是否为excel文件
if (
file[i].type ===
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
file[i].type === "application/vnd.ms-excel" ||
file[i].name.toLowerCase().endsWith(".xlsx") ||
file[i].name.toLowerCase().endsWith(".xls")
) {
formData.append("files", file[i], file[i].webkitRelativePath);
fileList.push(file[i]);
}
}
console.log("fileList.length :>> ", fileList.length);
if (fileList.length === 0) {
this.$message.error(`文件夹内没有excel格式文件,请确认!`);
document.querySelector("body").removeChild(input);
return;
}
// if (fileList.length < file.length) {
// this.$message.info(`已过滤非excel文件`);
// }
const url = "/wzdxcskwzdxcskwzdxcskwzdxcskwzdxcskwzdxcskwzdxcskwzdxcsk"; //我真的想吃烧烤
// 上传地址
const uploadUrl = window.config.VUE_APP_BASE_API + url;
console.log("uploadUrl :>> ", uploadUrl);
axios
.post(uploadUrl, formData, {
headers: {
"Content-Type": "multipart/form-data; ",
},
})
.then((response) => {
const data = response.data.data;
if (data === true) {
document.querySelector("body").removeChild(input);
}
});
};
}
总结: 此种方法的本质并不是真正的文件夹上传,用户选中目录时也只是按需将选中的目录文件挑出来,此外要注意兼容性。
以上。
参考链接1:https://developer.mozilla.org/zh-CN/docs/Web/API/HTMLInputElement/webkitdirectory
参考链接2:https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/input/file