Loading an image to a <img> from <input file>

Viewed 242889

I'm trying to load an image selected by the user through an element.

I added a onchange event handler to the input element like this:

<input type="file" name="picField" id="picField" size="24" onchange="preview_2(this);" alt=""/>

and the preview_2 function is:

var outImage ="imagenFondo";
function preview_2(what){
    globalPic = new Image();
    globalPic.onload = function() {
        document.getElementById(outImage).src = globalPic.src;
    }
    globalPic.src=what.value;
}

where outImage has the id value of the tag where I want the new picture to be loaded.

However, it appears that the onload never happens and it does not load anything to the html.

What should I do?

7 Answers

$('document').ready(function () {
    $("#imgload").change(function () {
        if (this.files && this.files[0]) {
            var reader = new FileReader();
            reader.onload = function (e) {
                $('#imgshow').attr('src', e.target.result);
            }
            reader.readAsDataURL(this.files[0]);
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="imgload" >
<img src="#" id="imgshow" align="left">

That works for me in jQuery.

ES2017 Way

// convert file to a base64 url
const readURL = file => {
    return new Promise((res, rej) => {
        const reader = new FileReader();
        reader.onload = e => res(e.target.result);
        reader.onerror = e => rej(e);
        reader.readAsDataURL(file);
    });
};

// for demo
const fileInput = document.createElement('input');
fileInput.type = 'file';
const img = document.createElement('img');
img.attributeStyleMap.set('max-width', '320px');
document.body.appendChild(fileInput);
document.body.appendChild(img);

const preview = async event => {
    const file = event.target.files[0];
    const url = await readURL(file);
    img.src = url;
};

fileInput.addEventListener('change', preview);

var outImage ="imagenFondo";
function preview_2(obj)
{
 if (FileReader)
 {
  var reader = new FileReader();
  reader.readAsDataURL(obj.files[0]);
  reader.onload = function (e) {
  var image=new Image();
  image.src=e.target.result;
  image.onload = function () {
   document.getElementById(outImage).src=image.src;
  };
  }
 }
 else
 {
      // Not supported
 }
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>preview photo</title>
</head>

<body>
<form>
 <input type="file" onChange="preview_2(this);"><br>
 <img id="imagenFondo" style="height: 300px;width: 300px;">
</form>
</body>
</html>

The easiest way to do it is by creating an Object URL

<input onChanged={(event)=>{ URL.createObjectURL(event!.target!.files[0]) }} />
Related