原理
- 手动用js创建一个type为file的DOM元素。
- 在读取到数据后,清空手动创建的DOM元素。返回得到的Promise类型的文件数据files。
const getFilesPromise = async () => {
let thePromise = new Promise((resolve, reject) => {
let theElement = document.createElement("input");
theElement.type = "file";
theElement.multiple = true;
theElement.onchange = async () => {
const theFiles = theElement.files;
theElement = null;
return resolve(theFiles);
};
theElement.click();
});
return thePromise;
};
const theFiles = await getFilesPromise();
const thisFiles = getFilesPromise();
thisFiles.then((res)=>{
})
说明
- 非侵入式是指想要用户上传一个数据,不必去改动DOM骨架。
- 由于用到了document,那么这些代码不能在非浏览器环境如node.js环境下使用。
- 由于该方法为异步方法,故而最好是在异步函数里使用。当然也可以在同步函数的最后一步里使用。
来源
- Promise
- promise在文件读取时使用的方法(promise的基本使用方法)
- input标签
- Document.createElement()