10

I'm trying to get image as Object of javascript on the client side to send it using jQuery

<html>
<body>
<script language="JavaScript">
function checkSize()
{
    im = new Image();
    im.src = document.Upload.submitfile.value;
if(!im.src)
    im.src = document.getElementById('submitfile').value;
    alert(im.src);
    alert(im.width);
    alert(im.height);
    alert(im.fileSize);

}
</script>
<form name="Upload" action="#" enctype="multipart/form-data" method="post">
   <p>Filename: <input type="file" name="submitfile" id="submitfile" />
   <input type="button" value="Send" onClick="checkSize();" />
</form>
</body>
</html>

But in this code only alert(im.src) is displaying src of file but alert(im.width),alert(im.height),alert(im.filesize) are not working properly and alerting 0, 0, undefined respectively. Kindly tell me how I can access image object using javascript?

Lucky
  • 16,787
  • 19
  • 117
  • 151
Adeel Akram
  • 390
  • 2
  • 4
  • 12
  • you ought to upload file to server and fetch data on server. JS will not be able to access your local file-system due to security restrictions – nkamm Nov 14 '12 at 06:16
  • @nkamm things working fine in case of IE but not for mozila and chrome,,, – Adeel Akram Nov 14 '12 at 06:21
  • Are you working on some local server? or just testing your code without server? nkamm is right..You can't access files locally like that in chrome and firfox due to security reasons. – MJQ Nov 14 '12 at 06:57

3 Answers3

9

The reason that im.fileSize is only working in IE is because ".fileSize" is only an IE property. Since you have code that works in IE, I would do a check for the browser and render your current code for IE and try something like this for other browsers.

var imgFile = document.getElementById('submitfile');
if (imgFile.files && imgFile.files[0]) {
    var width;
    var height;
    var fileSize;
    var reader = new FileReader();
    reader.onload = function(event) {
        var dataUri = event.target.result,
        img = document.createElement("img");
        img.src = dataUri;
        width = img.width;
        height = img.height;
        fileSize = imgFile.files[0].size;
        alert(width);
        alert(height);
        alert(fileSize);
   };
   reader.onerror = function(event) {
       console.error("File could not be read! Code " + event.target.error.code);
   };
   reader.readAsDataURL(imgFile.files[0]);
}

I haven't tested this code but it should work as long as I don't have some typo. For a better understanding of what I am doing here check out this link.

Blake Plumb
  • 6,779
  • 3
  • 33
  • 54
0

This is what I use and it works great for me. I save the image as a blob in mysql. When clicked, the file upload dialog appears, that is why i set the file input visibility to hidden and set its type to upload image files. Once the image is selected, it replaces the existing one, then I use the jquery post method to update the image in the database.

<div>
     <div><img id="logo" class="img-polaroid" alt="Logo" src="' . $row['logo'] . '" title="Click to change the logo" width="128">
     <input style="visibility:hidden;" id="logoupload" type="file" accept="image/* ">
</div>



  $('img#logo').click(function(){                           
    $('#logoupload').trigger('click');
    $('#logoupload').change(function(e){

      var reader = new FileReader(),
           files = e.dataTransfer ? e.dataTransfer.files : e.target.files,
            i = 0;

            reader.onload = onFileLoad;

             while (files[i]) reader.readAsDataURL(files[i++]);

              });

                function onFileLoad(e) {
                        var data = e.target.result;
                          $('img#logo').attr("src",data);
                          //Upload the image to the database
                           //Save data on keydown
                            $.post('test.php',{data:$('img#logo').attr("src")},function(){

                            });
                            }

                        });
gakuru
  • 111
  • 3
  • 6
0
$('#imagess').change(function(){

        var total_images=$('#total_images').val();


        var candidateimage=document.getElementById('imagess').value;
        formdata = false;
        var demo=document.getElementById("imagess").files;

        if (window.FormData) {
           formdata = new FormData();
           }

          var i = 0, len = demo.length, img, reader, file;
         for ( ; i < len; i++ ) {
          file = demo[i];
          if (file.type.match(/image.*/)) {
           if (formdata) {
            formdata.append("images", file);

           }
          } 
         }


        $('#preview').html('Uploading...');
        var url=SITEURL+"users/image_upload/"+total_images;

        $.ajax({
            url: url,
            type: "POST",
            data: formdata,
            processData: false,
            contentType: false,
            success: function (res) {
                $('#preview').html('');
                if (res == "maxlimit") {
                    alert("You can't upload more than 4 images");
                }
                else if (res == "error") {
                    alert("Image can't upload please try again.")
                }
                else {
                    $('#user_images').append(res);


                }
            }
           });  


    });
Vishnu Sharma
  • 1,357
  • 12
  • 11