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.