themhz
themhz

Reputation: 8424

How to get the Actual image width and height after drop event

I have been working on the following paradigm, in order to learn "how to drag an image from my desktop and drop it in my browser" works with Html 5. But after I drop the image, I just can't get the information about the image's actual width and height in the function handleFiles(files,n) where I alert it. Is this even possible? Can anyone help me?

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:og="http://ogp.me/ns#"
      xmlns:fb="http://www.facebook.com/2008/fbml"  xml:lang="el-gr" lang="el-gr" dir="ltr">
    <head>
       <meta http-equiv="content-type" content="text/html; charset=utf-8" />
       <title>Files javascript upload with drag and drop</title>
    </head>
<title>File(s) size</title>
</head>
<body>

<table>
    <tr>
        <td><input type="file" id="fileElem1"  name="fileElem1" accept="image/*" style="display:none" onchange="handleFiles(this.files)">
<div id="dropbox_1" style="width:200px;height:100px;border:1px solid blue;z-index=10;">  
    <div id="preview1"></div>
</div>
</td>
        <td><input type="file" id="fileElem2"  name="fileElem2" accept="image/*" style="display:none" onchange="handleFiles(this.files)">
<div id="dropbox_2" style="width:200px;height:100px;border:1px solid blue;">  <div id="preview2"></div></div></td>
        <td><input type="file" id="fileElem3"  name="fileElem3" accept="image/*" style="display:none" onchange="handleFiles(this.files)">
<div id="dropbox_3" style="width:200px;height:100px;border:1px solid blue;">  <div id="preview3"></div></div></td>
    </tr>
</table>

<input type="button" onclick="sendFiles()" value="send" >
<script>
    var dropbox1,dropbox2,dropbox3; 
    dropbox1 = document.getElementById("dropbox_1");
    dropbox1.addEventListener("dragenter", dragenter, false);
    dropbox1.addEventListener("dragover", dragover, false);
    dropbox1.addEventListener("drop", drop, false);

    dropbox2 = document.getElementById("dropbox_2");
    dropbox2.addEventListener("dragenter", dragenter, false);
    dropbox2.addEventListener("dragover", dragover, false);
    dropbox2.addEventListener("drop", drop, false);

    dropbox3 = document.getElementById("dropbox_3");
    dropbox3.addEventListener("dragenter", dragenter, false);
    dropbox3.addEventListener("dragover", dragover, false);
    dropbox3.addEventListener("drop", drop, false);


    var fileElem1 = document.getElementById("fileElem1");
        var fileElem2 = document.getElementById("fileElem2");   
        var fileElem3 = document.getElementById("fileElem3");


    function dragenter(e) {
      e.stopPropagation();
      e.preventDefault();
    }

    function dragover(e) {
      e.stopPropagation();
      e.preventDefault();
    } 

    function drop(e) {
      e.stopPropagation();
      e.preventDefault();

      var n=e.currentTarget.id.split("_");
      var dt = e.dataTransfer;
      var files = dt.files;

      handleFiles(files,n[1]);
    }

    var filesforupload = new Array(null,null,null);
    function handleFiles(files,n) {

      for (var i = 0; i < files.length; i++) {
        var file = files[i];
        var imageType = /image.*/;

        if (!file.type.match(imageType)) {
          continue;
        }

        var img = document.createElement("img");
        img.classList.add("obj");
        img.file = file;
        alert(img.width); // <- HERE I NEED TO GET THE width of the image
            img.style.zIndex=2;
            img.style.position="absolute";                  
            document.getElementById("dropbox_"+n).style.height="200";
        document.getElementById("preview"+n).innerHTML = "";
        document.getElementById("preview"+n).appendChild(img);

        var reader = new FileReader();
        reader.onload = (function(aImg) { return function(e) { aImg.src = e.target.result; }; })(img);
        reader.readAsDataURL(file);
        filesforupload[n-1]=file;
        //filesforupload.push(file);
        //sendFile(file);
      }
    }


    function sendFile(file) {
            var uri = "upload.php";
            var xhr = new XMLHttpRequest();
            var fd = new FormData();

            xhr.open("POST", uri, true);
            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    // Handle response.
                    alert(xhr.responseText); 
           // handle response.
                }
            };
        var reader = new FileReader();
            fd.append('fileElem', file);
            // Initiate a multipart/form-data upload
            xhr.send(fd);
        }


    function sendFiles(){

                for (var i=0; i<filesforupload.length; i++) {
           if(filesforupload[i]!=null)
                        sendFile(filesforupload[i]);
                }
    }


            dropbox1.ondrop = function(event) {
                event.stopPropagation();
                event.preventDefault(); 
        filesArray = event.dataTransfer.files;
            }


    function dump(obj) {
        var out = '';
        for (var i in obj) {
        out += i + ": " + obj[i] + "\n";
        }

        alert(out);        
    }
</script>
</body>
</html>

Upvotes: 3

Views: 2851

Answers (2)

themhz
themhz

Reputation: 8424

anyway I found the following solution by adding an id to the image + onload function on the image like this

img.addEventListener('load', function() { alert(document.getElementById('test').width); /* ... */ }, false);
img.id="test";

The order does not matter since the load event fires after the img object gets appended.

Here is the complete code.

<html xmlns="http://www.w3.org/1999/xhtml"
          xmlns:og="http://ogp.me/ns#"
          xmlns:fb="http://www.facebook.com/2008/fbml"  xml:lang="el-gr" lang="el-gr" dir="ltr">
        <head>
           <meta http-equiv="content-type" content="text/html; charset=utf-8" />
           <title>File(s) javascript upload with drag and drop</title>
        </head>
    <title>File(s) size</title>
    </head>
    <body>

    <table>
        <tr>
            <td><input type="file" id="fileElem1"  name="fileElem1" accept="image/*" style="display:none" onchange="handleFiles(this.files)">
    <div id="dropbox_1" style="min-width:200px;height:100px;border:1px solid blue;z-index=10;">  
        <div id="preview1"></div>
    </div>
    </td>
            <td><input type="file" id="fileElem2"  name="fileElem2" accept="image/*" style="display:none" onchange="handleFiles(this.files)">
    <div id="dropbox_2" style="width:200px;height:100px;border:1px solid blue;">  <div id="preview2"></div></div></td>
            <td><input type="file" id="fileElem3"  name="fileElem3" accept="image/*" style="display:none" onchange="handleFiles(this.files)">
    <div id="dropbox_3" style="width:200px;height:100px;border:1px solid blue;">  <div id="preview3"></div></div></td>
        </tr>
    </table>

    <input type="button" onclick="getthewidth()" value="send" >
    <script>
function getthewidth(){
alert(document.getElementById('test').width);
}
        var dropbox1,dropbox2,dropbox3; 
        dropbox1 = document.getElementById("dropbox_1");
        dropbox1.addEventListener("dragenter", dragenter, false);
        dropbox1.addEventListener("dragover", dragover, false);
        dropbox1.addEventListener("drop", drop, false);

        dropbox2 = document.getElementById("dropbox_2");
        dropbox2.addEventListener("dragenter", dragenter, false);
        dropbox2.addEventListener("dragover", dragover, false);
        dropbox2.addEventListener("drop", drop, false);

        dropbox3 = document.getElementById("dropbox_3");
        dropbox3.addEventListener("dragenter", dragenter, false);
        dropbox3.addEventListener("dragover", dragover, false);
        dropbox3.addEventListener("drop", drop, false);


        var fileElem1 = document.getElementById("fileElem1");
            var fileElem2 = document.getElementById("fileElem2");   
            var fileElem3 = document.getElementById("fileElem3");


        function dragenter(e) {
          e.stopPropagation();
          e.preventDefault();
        }

        function dragover(e) {
          e.stopPropagation();
          e.preventDefault();
        } 

        function drop(e) {
          e.stopPropagation();
          e.preventDefault();

          var n=e.currentTarget.id.split("_");
          var dt = e.dataTransfer;
          var files = dt.files;

          handleFiles(files,n[1]);
        }

        var filesforupload = new Array(null,null,null);
        function handleFiles(files,n) {

          for (var i = 0; i < files.length; i++) {
            var file = files[i];
            var imageType = /image.*/;

            if (!file.type.match(imageType)) {
              continue;
            }

            var img = document.createElement("img");
            img.classList.add("obj");
            img.file = file;
        img.addEventListener('load', function() { alert(document.getElementById('test').width); /* ... */ }, false);
        img.id="test";
        //alert(document.getElementById('test').id);
           // alert(img.width); // <- HERE I NEED TO GET THE width of the image
                img.style.zIndex=2;
                img.style.position="absolute";                  
                //document.getElementById("dropbox_"+n).style.height="200";
            document.getElementById("preview"+n).innerHTML = "";
            document.getElementById("preview"+n).appendChild(img);
            var reader = new FileReader();
            reader.onload = (function(aImg) { return function(e) { aImg.src = e.target.result; }; })(img);
            reader.readAsDataURL(file);
            filesforupload[n-1]=file;
            //filesforupload.push(file);
            //sendFile(file);
          }
        }


        function sendFile(file) {
                var uri = "upload.php";
                var xhr = new XMLHttpRequest();
                var fd = new FormData();

                xhr.open("POST", uri, true);
                xhr.onreadystatechange = function() {
                    if (xhr.readyState == 4 && xhr.status == 200) {
                        // Handle response.
                        alert(xhr.responseText); 
               // handle response.
                    }
                };
            var reader = new FileReader();
                fd.append('fileElem', file);
                // Initiate a multipart/form-data upload
                xhr.send(fd);
            }


        function sendFiles(){

                    for (var i=0; i<filesforupload.length; i++) {
               if(filesforupload[i]!=null)
                            sendFile(filesforupload[i]);
                    }
        }


                dropbox1.ondrop = function(event) {
                    event.stopPropagation();
                    event.preventDefault(); 
            filesArray = event.dataTransfer.files;
                }


        function dump(obj) {
            var out = '';
            for (var i in obj) {
            out += i + ": " + obj[i] + "\n";
            }

            alert(out);        
        }
    </script>
    </body>
    </html>

Upvotes: 0

ndpu
ndpu

Reputation: 22561

Try it this way (updated with 100 ms timeout):

    reader.onload = (function(aImg) {
        return function(e) {
            aImg.src = e.target.result;
            setTimeout(function() {
                console.log(aImg.width);  // right now file already loaded...
            }, 100);
        };
    })(img);

http://jsfiddle.net/wVB3V/3/

Upvotes: 3

Related Questions