6

I want to preview an uploaded image file in a div. I have done a bit of research and I have found this piece of code from this post, it is the code to preview an uploaded image file, but in an <img> tag:

<script type="text/javascript">
    function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('#blah').attr('src', e.target.result);
            }

            reader.readAsDataURL(input.files[0]);
        }
    }
</script>

The associated HTML:

<body>
    <form id="form1" runat="server">
        <input type='file' onchange="readURL(this);" />
        <img id="blah" src="#" alt="your image" />
    </form>
</body>

Very cool. However, what I want is to display the uploaded image as the background image of a div, an example of which would be like this:

<div class="image" style="background-image:url('');"></div>

I know that, logically, I would have to replace

$('#blah').attr('src', e.target.result);

with something like

$('div.image').attr('style', e.target.result);.

But how to make the path of the image go into the value of the 'background-image' property?

And yes, do I need to link to the JQuery library for this?

Thank you.

Community
  • 1
  • 1
Hemkesh Molla
  • 109
  • 1
  • 3
  • 8

1 Answers1

14

You could use CSS shorthand just like in a CSS file. I recommend the following to avoid repeating and alignment issues:

<script type="text/javascript">
    function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('#objectID').css('background', 'transparent url('+e.target.result +') left top no-repeat');
            }

            reader.readAsDataURL(input.files[0]);
        }
    }
</script>

The change is the line like this

$('#objectID').css('background', 'transparent url('+e.target.result +') left top no-repeat');
Ding
  • 2,987
  • 1
  • 14
  • 26
  • Thank you. It works perfectly. Just to mention, in my question above, I have changed the div's 'id' attribute to 'class' instead, probably while you were writing this answer. So, instead of using '$('#image')...', I am using '$(div.image)...'. But anyways, :) thank you again. – Hemkesh Molla May 01 '13 at 05:55