Skip to content

Commit

Permalink
feat(utils): 新增 chooseFile 选择文件
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Nov 17, 2020
1 parent a4db5f9 commit 128b650
Show file tree
Hide file tree
Showing 4 changed files with 66 additions and 12 deletions.
30 changes: 18 additions & 12 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions src/utils/chooseFile.test.ts
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)
})
})
40 changes: 40 additions & 0 deletions src/utils/chooseFile.ts
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()
})
}
1 change: 1 addition & 0 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export * from 'lodash-es'
// @index(['./**/*.ts', '!./**/*.test.*'], f => `export * from '${f.path}'`)
export * from './base64'
export * from './bindEvent'
export * from './chooseFile'
export * from './createSubmit'
export * from './createUrlQueryString'
export * from './dedent'
Expand Down

0 comments on commit 128b650

Please sign in to comment.