-
Notifications
You must be signed in to change notification settings - Fork 22
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
4 changed files
with
66 additions
and
12 deletions.
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
import { chooseFile } from './chooseFile' | ||
|
||
describe('chooseFile', () => { | ||
test('ok', () => { | ||
expect(chooseFile).toBe(chooseFile) | ||
}) | ||
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
import { bindEvent } from './bindEvent' | ||
import { LiteralUnion } from '../types' | ||
|
||
/** | ||
* 选择文件。 | ||
* | ||
* @param accept 接受的文件类型 | ||
* @param multiple 是否多选 | ||
* @returns 返回选中的文件列表 | ||
*/ | ||
export async function chooseFile( | ||
accept: LiteralUnion<'image', string>, | ||
multiple = false, | ||
): Promise<File[]> { | ||
return new Promise(resolve => { | ||
let input = document.createElement('input') | ||
input.style.all = 'unset' | ||
input.style.position = 'fixed' | ||
input.style.top = '0px' | ||
input.style.clip = 'rect(0, 0, 0, 0)' | ||
input.style.webkitUserSelect = 'text' | ||
// @ts-ignore | ||
input.style.MozUserSelect = 'text' | ||
// @ts-ignore | ||
input.style.msUserSelect = 'text' | ||
input.style.userSelect = 'text' | ||
input.type = 'file' | ||
input.accept = accept === 'image' ? '.jpg,.jpeg,.png,.gif' : accept | ||
input.multiple = multiple | ||
document.body.appendChild(input) | ||
const unbindChange = bindEvent(input)('change', () => { | ||
const files = input.files || [] | ||
unbindChange() | ||
document.body.removeChild(input) | ||
input = null as any | ||
resolve(files as any) | ||
}) | ||
input.click() | ||
}) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters