| 110 | * @returns |
| 111 | */ |
| 112 | export async function selectFile(accept?: string): Promise<File> { |
| 113 | if (typeof document === 'undefined') { |
| 114 | throw new Error('document is undefined') |
| 115 | } |
| 116 | |
| 117 | return new Promise((resolve, reject) => { |
| 118 | const input = document.createElement('input') |
| 119 | input.style.display = 'none' |
| 120 | input.type = 'file' |
| 121 | if (accept) { |
| 122 | input.accept = accept |
| 123 | } |
| 124 | |
| 125 | input.onchange = () => { |
| 126 | if (input.files && input.files.length > 0) { |
| 127 | resolve(input.files[0]) |
| 128 | } else { |
| 129 | reject(new Error('未选择文件')) |
| 130 | } |
| 131 | cleanup() |
| 132 | } |
| 133 | |
| 134 | input.onerror = (error) => { |
| 135 | reject(error) |
| 136 | cleanup() |
| 137 | } |
| 138 | |
| 139 | const cleanup = () => { |
| 140 | input.onchange = null |
| 141 | input.onerror = null |
| 142 | input.remove() |
| 143 | } |
| 144 | |
| 145 | document.body.appendChild(input) |
| 146 | input.click() |
| 147 | }) |
| 148 | } |
| 149 | |
| 150 | /** |
| 151 | * 扁平文件树去根 |