How to check file MIME type with javascript before upload?

前端 未结 9 2225
挽巷
挽巷 2020-11-22 03:50

I have read this and this questions which seems to suggest that the file MIME type could be checked using javascript on client side. Now, I understand that the real validati

9条回答
  •  执念已碎
    2020-11-22 04:53

    If you just want to check if the file uploaded is an image you can just try to load it into tag an check for any error callback.

    Example:

    var input = document.getElementsByTagName('input')[0];
    var reader = new FileReader();
    
    reader.onload = function (e) {
        imageExists(e.target.result, function(exists){
            if (exists) {
    
                // Do something with the image file.. 
    
            } else {
    
                // different file format
    
            }
        });
    };
    
    reader.readAsDataURL(input.files[0]);
    
    
    function imageExists(url, callback) {
        var img = new Image();
        img.onload = function() { callback(true); };
        img.onerror = function() { callback(false); };
        img.src = url;
    }
    

提交回复
热议问题