15

The HTML code for image file input:

<input type="file" autocomplete="off" name="background-image" accept="image/*" />

The destination div block where I want to dynamically set the background image:

<div class="clock"></div>

The jQuery function I'm currently using for setting image file uploaded as div background image:

$(".background>div>input[type=file]").change(function () {
    var fileExtension = ['jpeg', 'jpg', 'png', 'gif', 'bmp'];
    if ($.inArray($(this).val().split('.').pop().toLowerCase(), fileExtension) == -1) {
        alert("Only '.jpeg','.jpg', '.png', '.gif', '.bmp' formats are allowed.");
    }
    else {
        $(".clock").css("background-image",'url("' + $(".background>div>input[type=file]").val() + '")');
    }
});

The issue is that the background-image is not being set. This may possibly be because when I checked with browser inspector, the file upload is not containing file url. Note: The background-color of .clock is set to white initially.Also I'd not like to use a server since my intention is to keep it as client side only application.

RBk
  • 189
  • 1
  • 1
  • 7

3 Answers3

57

This may solve your problem

JS FIDDLE

HTML

<input type='file' id='getval' name="background-image" /><br/><br/>
<div id='clock'></div>

CSS

#clock{
   background-image:url('');
   background-size:cover;
   background-position: center;
   height: 250px; width: 250px;
   border: 1px solid #bbb;
}

PURE JAVASCRIPT

document.getElementById('getval').addEventListener('change', readURL, true);
function readURL(){
   var file = document.getElementById("getval").files[0];
   var reader = new FileReader();
   reader.onloadend = function(){
      document.getElementById('clock').style.backgroundImage = "url(" + reader.result + ")";        
   }
   if(file){
      reader.readAsDataURL(file);
    }else{
    }
}
Malik Naik
  • 1,472
  • 14
  • 16
11

It's small way to do this without using FileReader.

http://jsfiddle.net/PuneetChawla/vqn7r0nj/

HTML

<input type='file' id='getval' name="background-image" onchange="readURL(event)" /><br/><br/>
<div id='clock'></div>

CSS

#clock{
           background-image:url('');
           background-size:cover;
           background-position: center;
           height: 250px; width: 250px;
           border: 1px solid #bbb;
            }

JavaScript

function readURL(event){
         var getImagePath = URL.createObjectURL(event.target.files[0]);
         $('#clock').css('background-image', 'url(' + getImagePath + ')');
        }

Explanation - The URL.createObjectURL() static method creates a DOMString containing an URL representing the object given in parameter.

Puneet Chawla
  • 5,729
  • 4
  • 16
  • 33
  • what about the if(file){ } condition? – RBk Jul 11 '15 at 07:28
  • Rijurekh - I didn't added that condition, Now i just specified to get image and display in div in short way. That logic can be easily implemented. Just try it by ownself otherwise i will update my answer with adding that condition. – Puneet Chawla Jul 11 '15 at 07:33
  • You just need to add a condition to check extension is correct or not like .jpge or .gif. i don't think there is need to any other logic that needs to be implemented. – Puneet Chawla Jul 11 '15 at 07:40
1

var loadFile = function(event) {
    var output = document.getElementById('output');
    output.style.backgroundImage= "url("+URL.createObjectURL(event.target.files[0])+")";
  };
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
<input type="file" accept="image/*" onchange="loadFile(event)">
<div style="width: 500px;height: 500px;" id="output"></div>
</body>
</html>
  • Please edit this answer to explain why your code works and how it solves the OP's issue – jro Mar 30 '19 at 09:32