jQuery how to check if uploaded file is an image without checking extensions?

前端 未结 7 1276
有刺的猬
有刺的猬 2021-01-31 09:17

Newbie here. The problem is that I currently have written a method which checks uploaded file size and extension in order to validate it. However, checking extensions is not a s

7条回答
  •  既然无缘
    2021-01-31 10:04

    Try something like this:

    JavaScript

    const file = this.files[0];
    const  fileType = file['type'];
    const validImageTypes = ['image/gif', 'image/jpeg', 'image/png'];
    if (!validImageTypes.includes(fileType)) {
        // invalid file type code goes here.
    }
    

    jQuery

    var file = this.files[0];
    var fileType = file["type"];
    var validImageTypes = ["image/gif", "image/jpeg", "image/png"];
    if ($.inArray(fileType, validImageTypes) < 0) {
         // invalid file type code goes here.
    }
    

提交回复
热议问题