How to Preview Image, get file size, image height

2018-12-31 07:04发布

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

7条回答
看淡一切
2楼-- · 2018-12-31 07:27

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("<img src='" + img.src + "' />");
                console.log("Finished reading Image");
        		}});
        };
        
        img.src = fr.result;
    };
    
    fr.readAsDataURL(this.files[0]);
    
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" accept="image/*" capture="camera">
<div id='result'>Please choose a file to view it. <br/>(Tested successfully on Chrome - 100% SUCCESS RATE)</div>

(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/)

查看更多
登录 后发表回答