Js judges whether the type of uploaded file is an image

You can use the type property of the JavaScript File object to determine whether the file type is an image. Here is a simple sample code:

function isImage(file) {
    
    
  return file.type.startsWith('image/');
}

In this function, we use the type property of the File object to get the type of the file. Then, use the startsWith method to determine whether the type starts with 'image/', if yes, it means that the file type is an image, and return true; otherwise, it means that the file type is not an image, and return false.

You can call this function where the file type needs to be judged, and pass in the file object that needs to be judged to make the judgment. For example:

const inputFile = document.getElementById('myFileInput');
const file = inputFile.files[0];
console.log(isImage(file)); // 输出 true 或 false

In the above code, first obtain a file input element through getElementById, then obtain the file object selected by the user, assuming it is the first file, then call the isImage function to determine whether the file type is an image, and output the result to the console .

Guess you like

Origin blog.csdn.net/qq_44848480/article/details/132148410
Recommended