How to make input `type=file` to accept only images React
Asked Answered
D

4

6
<Input
  id="image"
  type="file"
  accept="image/*"
  onChange={(event) =>
    getBase64(event.target.files[0])
      .then((file) => this.setState({ image: file })
  )}
/> 

But it does accept other files too, what should I change to make it accept only images?

Dewberry answered 6/8, 2018 at 8:4 Comment(2)
What do you mean by "it does accept other files too" and how is this related to React only? Do you want to validate the file type before uploading it to your server?Adrien
React has an <input> element, not <Input> - you must be using some library that ignores the accept prop. Which library are you using?Entomology
W
6

To set the accept attribute on an <Input /> you need to use inputPropslike this

<Input type="file" inputProps={{ accept: 'image/*' }} />

EDIT Looking at this some months later and reading @Aprillions comment I think it would be good to clarify this is Material-UI and not pure React

Washtub answered 10/1, 2020 at 11:1 Comment(0)
A
2

The problem may be that you have passed or modified the props after changed the accept attribute. so, you have a solution or that. change the attribute order you passed. that means you can pass the accept attribute as the last attribute, like below.

<Input
 id="image"
 type="file"
 onChange={event =>
  getBase64(event.target.files[0]).then(file =>
   this.setState({ image: file })
 )
 accept="image/*"
}
/> 
Abut answered 1/12, 2020 at 8:34 Comment(0)
I
1

File inputs have an accept attribute which you can use for this (docs).

Im answered 6/8, 2018 at 8:54 Comment(2)
you mean this, accept="image/*" even after this attribute it does allow to select other filesDewberry
@AmarThapa that will specify that only files with an image MIME type can be uploadedIm
C
0
<input type="file" accept="image/*" />

this make input image only

Crosshatch answered 7/8, 2024 at 17:15 Comment(1)
it accept all types of imagesCrosshatch

© 2022 - 2025 — McMap. All rights reserved.