ZeroZerg ZeroZerg - 1 year ago 76
CSS Question

How to get the size of the image which is uploaded by <input>

function changeFile() {
var preview = document.getElementById("previewDiv"); = "";

var element = document.getElementById("ads_files");
var files = element.files;

var file = files[0];


var reader = new FileReader();
reader.onload = loadFinished;

function loadFinished(event) {
var data =; = 'url(' + data + ')';

#previewDiv {
border: 2px solid rgb(204, 204, 204);
width: 250px;
height: 200px;
background-size: 100% 100%;

<script src=""></script>
<input type="file" id="ads_files" name="file" onchange=changeFile() />

<div id="previewDiv">

The code above is to upload a picture and show it as the background of div. It works perfectly.

Now I wish to upload the picture with proper width and height. So I need to get the size of the upload picture (The other pictures won't be uploaded to server).

I've searched some solutions on internet. It seems that document.getElementById("ads_files").value may get the path of the file after the image is uploaded. Then use Image.src=document.getElementById("ads_files") to load the image and get the size with function of Image.

But the question is that the value is a fake path like c:\fakepath\10256530_503531203106865_63236440322903725_n.jpg (I'm using Mac!!!!). Of course the program won't work.

I bet the work can be done locally but I don't know how to do it.

Any good idea?

Answer Source

Here is how you retrieve the image dimensions, add these to your loadFinished() function

var image = new Image();
image.src = data;
image.onload = function() {
    console.log(image.naturalWidth, image.naturalHeight);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download