How to check file MIME type with javascript before upload?

前端 未结 9 2112
挽巷
挽巷 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:39

    As stated in other answers, you can check the mime type by checking the signature of the file in the first bytes of the file.

    But what other answers are doing is loading the entire file in memory in order to check the signature, which is very wasteful and could easily freeze your browser if you select a big file by accident or not.

    /**
     * Load the mime type based on the signature of the first bytes of the file
     * @param  {File}   file        A instance of File
     * @param  {Function} callback  Callback with the result
     * @author Victor www.vitim.us
     * @date   2017-03-23
     */
    function loadMime(file, callback) {
        
        //List of known mimes
        var mimes = [
            {
                mime: 'image/jpeg',
                pattern: [0xFF, 0xD8, 0xFF],
                mask: [0xFF, 0xFF, 0xFF],
            },
            {
                mime: 'image/png',
                pattern: [0x89, 0x50, 0x4E, 0x47],
                mask: [0xFF, 0xFF, 0xFF, 0xFF],
            }
            // you can expand this list @see https://mimesniff.spec.whatwg.org/#matching-an-image-type-pattern
        ];
    
        function check(bytes, mime) {
            for (var i = 0, l = mime.mask.length; i < l; ++i) {
                if ((bytes[i] & mime.mask[i]) - mime.pattern[i] !== 0) {
                    return false;
                }
            }
            return true;
        }
    
        var blob = file.slice(0, 4); //read the first 4 bytes of the file
    
        var reader = new FileReader();
        reader.onloadend = function(e) {
            if (e.target.readyState === FileReader.DONE) {
                var bytes = new Uint8Array(e.target.result);
    
                for (var i=0, l = mimes.length; i Browser:" + file.type);
                }
    
                return callback("Mime: unknown 
    Browser:" + file.type); } }; reader.readAsArrayBuffer(blob); } //when selecting a file on the input fileInput.onchange = function() { loadMime(fileInput.files[0], function(mime) { //print the output to the screen output.innerHTML = mime; }); };
    
    

提交回复
热议问题