转载于:选择文件的js方法 - 蛙仔 - 博客园
let fileInputEle;let fileInputHandlerDefer = {};// 选择文件export const getFile = (limitTypes, multiple) => {// 创建 input 节点fileInputEle = document.createElement("input");// 将 input 类型改为文件 type = filefileInputEle.setAttribute("type", "file");// 不显示fileInputEle.style.display = "none";// 内容改变事件fileInputEle.addEventListener("change", () => {if (fileInputEle.files && fileInputEle.files.length) {// multiple :true 可以多图片上传, false 单图片上传if (multiple) {fileInputHandlerDefer.resolve(fileInputEle.files);} else {fileInputHandlerDefer.resolve(fileInputEle.files[0]);}} else {fileInputHandlerDefer.reject();}});// 重置 multiple, accept 属性fileInputEle.removeAttribute("multiple");fileInputEle.removeAttribute("accept");fileInputEle.value = "";if (multiple) {fileInputEle.setAttribute("multiple", "multiple");}// 设置上传图片约束if (limitTypes && limitTypes.length) {fileInputEle.setAttribute("accept",limitTypes.map(one => (`.${one}`)).join(","));}return new Promise((resolve, reject) => {fileInputHandlerDefer.resolve = resolve;fileInputHandlerDefer.reject = reject;fileInputEle.click();});};
测试
getFile(['jpg','png'], false).then((files) => {console.log(files)})