Upload Only from Images

Asked

Viewed 12,739 times

5

How to upload images only(.png and .jpeg)? Do not allow the choice of another file type.

I’m using as per below:

 <input type="file" name="arquivos" class="btn btn-success" multiple/>

At the time of selecting the photos I do not want to allow the choice of other file types.

2 answers

7


Tag <input>

<input type="file" name="arquivos" class="btn btn-success"  accept="image/png, image/jpeg"  multiple /> 

Now the button will accept only image type files with . jpeg and . png (won’t even show other options in the file selection area)

Add to <form> onsubmit="Checkfiles(this)" and put a id in his input.

using together a javascript code:

function Checkfiles(){
    var fup = document.getElementById('filename');
    var fileName = fup.value;
    var ext = fileName.substring(fileName.lastIndexOf('.') + 1);

    if(ext =="jpeg" || ext=="png"){
        return true;
    }
    else{
        return false;
    }
}
  • Thank you! It worked, however, on the file selection screen, on the option to change the file type, allows you to change to "All Files" in this way you can select any file. Is there any way to block it??

  • Add: accept="image/png, image/jpeg" in the input from the file selection screen.

  • 1

    I already added but as I said: allows the change to "All Files" would block it??

  • I’m using this: <input type="file" name="files" class="btn btn-Success" Accept="image/png, image/jpeg" Multiple />

  • enter the code of opção de mudar o tipo de arquivo

  • There is no code to change the file type. I mean when we click on the input that opened the selection screen to choose the files as link (http://www.tickimg.com.br/uploads/_example.png)

  • 1

    I don’t trust to use validation in this way, because the user who knows HTML can remove this configuration and upload any file. There are ways to do this validation via PHP which is much safer( if you are using this language).

  • Where do I put onsubmit="Checkfiles(this)" ? No form?

Show 3 more comments

1

For those of you still doing research on this, I did it in another way that maybe you can help. Obs: files would be the input.

const validTypes = ['png', 'PNG', 'jpg', 'JPG', 'jpeg', 'JPEG', 'pdf', 'PDF']

const valid = validTypes.filter(e=>{ if(files[0].name.includes(e)) return e })

if (!files[0].name.includes(valid[0])) {
    alert('Por favor insira o imagens nos formatos JPG, PNG e PDF')
    return
}

`

Browser other questions tagged

You are not signed in. Login or sign up in order to post.