Refactor uploadFile to extract functionality
This commit is contained in:
parent
836693f04a
commit
df5d77729d
1 changed files with 11 additions and 6 deletions
17
src/App.tsx
17
src/App.tsx
|
@ -82,6 +82,15 @@ function downloadUri(uri: string, filename: string) {
|
|||
downloadAnchor.click();
|
||||
}
|
||||
|
||||
async function eventToAsync<EventType extends keyof HTMLElementEventMap>(element: HTMLElement, eventType: EventType) {
|
||||
const abortController = new AbortController();
|
||||
const evt = await new Promise<HTMLElementEventMap[EventType]>((resolve) => {
|
||||
element.addEventListener(eventType, (evt) => resolve(evt), {signal: abortController.signal});
|
||||
})
|
||||
abortController.abort();
|
||||
return evt;
|
||||
}
|
||||
|
||||
/**
|
||||
* This appears to be the best way to upload a file.
|
||||
*/
|
||||
|
@ -89,14 +98,10 @@ async function uploadFile() {
|
|||
const uploadInput = document.createElement("input");
|
||||
uploadInput.type = "file";
|
||||
uploadInput.click();
|
||||
const abortController = new AbortController();
|
||||
await new Promise((resolve) => uploadInput.addEventListener("change", resolve, {signal: abortController.signal}));
|
||||
abortController.abort();
|
||||
await eventToAsync(uploadInput, "change");
|
||||
const files = uploadInput.files;
|
||||
if (files?.length !== 1) return;
|
||||
const file = files[0];
|
||||
console.log(file.name);
|
||||
return file;
|
||||
return files[0];
|
||||
}
|
||||
|
||||
function App() {
|
||||
|
|
Loading…
Add table
Reference in a new issue