Get file size, image width and height before upload

前端 未结 7 1344
自闭症患者
自闭症患者 2020-11-22 03:50

How can I get the file size, image height and width before upload to my website, with jQuery or JavaScript?

7条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 04:31

    So I started experimenting with the different things that FileReader API had to offer and could create an IMG tag with a DATA URL.

    Drawback: It doesn't work on mobile phones, but it works fine on Google Chrome.

    $('input').change(function() {
        
        var fr = new FileReader;
        
        fr.onload = function() {
            var img = new Image;
            
            img.onload = function() { 
    //I loaded the image and have complete control over all attributes, like width and src, which is the purpose of filereader.
                $.ajax({url: img.src, async: false, success: function(result){
                		$("#result").html("READING IMAGE, PLEASE WAIT...")
                		$("#result").html("");
                    console.log("Finished reading Image");
            		}});
            };
            
            img.src = fr.result;
        };
        
        fr.readAsDataURL(this.files[0]);
        
    });
    
    
    
    Please choose a file to view it.
    (Tested successfully on Chrome - 100% SUCCESS RATE)

    (see this on a jsfiddle at http://jsfiddle.net/eD2Ez/530/)
    (see the original jsfiddle that i added upon to at http://jsfiddle.net/eD2Ez/)

提交回复
热议问题