scrapbox-file-uploader
2022-04-17 14:14:38 ファイルが選択されていなかったらundefinedを返す
code:mod.ts
/// <reference no-default-lib="true" />
/// <reference lib="esnext" />
/// <reference lib="dom" />
export interface UploadInit {
/** uploadできるファイルの種類 */
accept: string;
/** 複数個ファイルをuploadできるかどうか */
multiple?: boolean;
}
export function upload(
init: Omit<UploadInit, "multiple"> & { multiple?: false },
): Promise<File | undefined>;
export function upload(
init: Omit<UploadInit, "multiple"> & { multiple: true },
): Promise<FileList | undefined>;
export function upload(init: UploadInit): Promise<FileList | File | undefined> {
return new Promise((resolve, reject) => {
const input = document.createElement("input");
input.type = "file";
input.accept = init.accept;
input.multiple = init.multiple ?? false;
input.addEventListener("change", () => {
resolve(
init.multiple === true
? (!input.files ? undefined : input.files.length === 0 ? undefined : input.files)
: (input.files?.0 ?? undefined), );
});
input.addEventListener("error", reject);
input.click();
});
}
code:mod.js
function i(n){return new Promise((t,l)=>{const e=document.createElement("input");e.type="file",e.accept=n.accept,e.multiple=n.multiple??!1,e.addEventListener("change",()=>{t(n.multiple===!0?e.files?e.files.length===0?void 0:e.files:void 0:e.files?.0??void 0)}),e.addEventListener("error",l),e.click()})}export{i as upload};