[html] How to allow <input type="file"> to accept only image files?

I need to upload only image file through <input type="file"> tag.

Right now, it accepts all file types. But, I want to restrict it to only specific image file extensions which include .jpg, .gif etc.

How can I achieve this functionality?

This question is related to html

The answer is


If you want to upload multiple images at once you can add multiple attribute to input.

_x000D_
_x000D_
upload multiple files: <input type="file" multiple accept='image/*'>
_x000D_
_x000D_
_x000D_


This can be achieved by

<input type="file" accept="image/*" /> 

But this is not a good way. you have to code on the server side to check the file an image or not.

Check if image file is an actual image or fake image

if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    }
    else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}

For more reference, see here

http://www.w3schools.com/tags/att_input_accept.asp
http://www.w3schools.com/php/php_file_upload.asp


you can use accept attribute for <input type="file"> read this docs http://www.w3schools.com/tags/att_input_accept.asp


Use it like this

<input type="file" accept=".png, .jpg, .jpeg" />

It worked for me

https://jsfiddle.net/ermagrawal/5u4ftp3k/


Steps:
1. Add accept attribute to input tag
2. Validate with javascript
3. Add server side validation to verify if the content is really an expected file type

For HTML and javascript:

<html>
<body>
<input name="image" type="file" id="fileName" accept=".jpg,.jpeg,.png" onchange="validateFileType()"/>
<script type="text/javascript">
    function validateFileType(){
        var fileName = document.getElementById("fileName").value;
        var idxDot = fileName.lastIndexOf(".") + 1;
        var extFile = fileName.substr(idxDot, fileName.length).toLowerCase();
        if (extFile=="jpg" || extFile=="jpeg" || extFile=="png"){
            //TO DO
        }else{
            alert("Only jpg/jpeg and png files are allowed!");
        }   
    }
</script>
</body>
</html>

Explanation:

  1. The accept attribute filters the files that will be displayed in the file chooser popup. However, it is not a validation. It is only a hint to the browser. The user can still change the options in the popup.
  2. The javascript only validates for file extension, but cannot really verify if the select file is an actual jpg or png.
  3. So you have to write for file content validation on server side.

i know i'm late but this might help. you can add specific type of image or other file type and do validation in your code :

<input style="margin-left: 10px; margin-top: 5px;" type="file" accept="image/x-png,image/jpeg,application/pdf" (change)="handleFileInput($event,'creditRatingFile')" name="creditRatingFile" id="creditRatingFile">

      handleFileInput(event) {
    console.log(event);
    const file = event.target.files[0];
    if (file.size > 2097152) {
        throw err;
    } else if (
      file.type !== "application/pdf"  &&
      file.type !== "application/wps-office.pdf"   && 
      file.type !== 'application/pdf'  && file.type !== 'image/jpg'  && file.type !== 'image/jpeg'  && file.type !== "image/png"
    ) {
throw err;
    } else {
      
        console.log('file valid')
    }
  }

Using type="file" and accept="image/*" (or the format you want), allow the user to chose a file with specific format. But you have to re check it again in client side, because the user can select other type of files. This works for me.

<input #imageInput accept="image/*" (change)="processFile(imageInput)" name="upload-photo" type="file" id="upload-photo" />

And then, in your javascript script

processFile(imageInput) {
    if (imageInput.files[0]) {
      const file: File = imageInput.files[0];
      var pattern = /image-*/;

      if (!file.type.match(pattern)) {
        alert('Invalid format');
        return;
      }

      // here you can do whatever you want with your image. Now you are sure that it is an image
    }
  }

Simple and powerful way(dynamic accept)

place formats in array like "image/*"

_x000D_
_x000D_
var upload=document.getElementById("upload");
var array=["video/mp4","image/png"];
upload.accept=array;
upload.addEventListener("change",()=>{

console.log(upload.value)
})
_x000D_
<input type="file" id="upload" >
_x000D_
_x000D_
_x000D_


Using this:

<input type="file" accept="image/*">

works in both FF and Chrome.


In html;

<input type="file" accept="image/*">

This will accept all image formats but no other file like pdf or video.

But if you are using django, in django forms.py;

image_field = forms.ImageField(Here_are_the_parameters)