Skip to content

Commit

Permalink
fix: do not allow to upload files with invalid formats
Browse files Browse the repository at this point in the history
  • Loading branch information
LauraBeatris committed Feb 18, 2021
1 parent ad427a6 commit 9232a5d
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 5 deletions.
29 changes: 29 additions & 0 deletions src/__tests__/upload.js
Original file line number Diff line number Diff line change
Expand Up @@ -163,3 +163,32 @@ test('should call onChange/input bubbling up the event when a file is selected',
expect(onInputInput).toHaveBeenCalledTimes(1)
expect(onInputForm).toHaveBeenCalledTimes(1)
})

test('should not upload file with invalid unaccepted format', () => {
const file = new File(['hello'], 'hello.png', {type: 'image/png'})

const {element} = setup('<input type="file" accept="image/jpg" />')

userEvent.upload(element, file)

expect(element.files[0]).toBeUndefined()
expect(element.files.item(0)).toBeNull()
expect(element.files).toHaveLength(0)
})

test('should not upload multiple files with invalid unaccepted formats', () => {
const files = [
new File(['hello'], 'hello.txt', {type: 'text/plain'}),
new File(['there'], 'there.pdf', {type: 'application/pdf'}),
]

const {element} = setup(`
<input id="files" type="file" accept="image/jpeg,image/png" multiple />
`)

userEvent.upload(element, files)

expect(element.files[0]).toBeUndefined()
expect(element.files.item(0)).toBeNull()
expect(element.files).toHaveLength(0)
})
26 changes: 21 additions & 5 deletions src/upload.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,32 @@ import {blur} from './blur'
import {focus} from './focus'

function upload(element, fileOrFiles, init) {
if (element.disabled) return
const hasFileWithInvalidType =
!Array.isArray(fileOrFiles) &&
element.accept &&
!element.accept.includes(element.type)

if (hasFileWithInvalidType || element.disabled) return

click(element, init)

const input = element.tagName === 'LABEL' ? element.control : element

const files = (Array.isArray(fileOrFiles)
? fileOrFiles
: [fileOrFiles]
).slice(0, input.multiple ? undefined : 1)
let files = []

if (Array.isArray(fileOrFiles)) {
files = element.accept
? fileOrFiles.filter(file => element.accept.includes(file.type))
: fileOrFiles
} else {
files = [fileOrFiles]
}

const hasFilesWithInvalidTypes = files.length === 0

if (hasFilesWithInvalidTypes) return

files = files.slice(0, input.multiple ? undefined : 1)

// blur fires when the file selector pops up
blur(element, init)
Expand Down

0 comments on commit 9232a5d

Please sign in to comment.