Nicholas Ribeiro
Nicholas Ribeiro

Reputation: 1

how to create a validation to check image type in typescript

can someone tell me how to create a method to check the image type?

I'm creating an image component in which only the following types will be accepted [JPEG GIF, including animated GIFs, PNG SVG,BMP]

Upvotes: 0

Views: 1104

Answers (2)

Rakesh
Rakesh

Reputation: 11

What I understood from the question that you need to accept only certain file types, you can easily do it in html as your input type will be file to accept a file so use accept attribute of input type file where you can pass the extensions you need to support. Refere w3school tutorials - https://www.w3schools.com/tags/att_input_accept.asp

<input type="file" id="img" name="img" accept="image/*">

Upvotes: 0

cc_haensel
cc_haensel

Reputation: 110

I don't know how to do it in Angular, but in native JS you can get the file type as an attribute of the file object.

I think there will be something similar in Angular.

const onchange = (event) => {
    const filetype = event.target.files[0].type;
    console.log(filetype);
}

or more general:

const elem = document.getElementById('your-file-input');
console.log(elem.files[0].type);

This will log something like "image/png" or "application/pdf" which you then can check.

Upvotes: 1

Related Questions