Question

I'm working on a facebook tab that accepts some text and also a picture using an html fileUpload component, the idea is that when the user selects a picture in the fileUpload component, the image they select appears on the page as a way of previewing the picture before uploading it to the server. I tried fectching the image url using val(), but for security reasons, browsers do not give the complete url of a local file. Is there a way to do this using either php or jquery?

Thanks

Was it helpful?

Solution

I believe this is what you're looking for:

function handleFiles(files) {
  for (var i = 0; i < files.length; i++) {
    var file = files[i];
    var imageType = /image.*/;

    if (!file.type.match(imageType)) {
      continue;
    }

    var img = document.createElement("img");
    img.classList.add("obj");
    img.file = file;
    preview.appendChild(img);

    var reader = new FileReader();
    reader.onload = (function(aImg) { return function(e) { aImg.src = e.target.result; }; })(img);
    reader.readAsDataURL(file);
  }
}

You might also be interested in reading other examples, like this one.

Edit: This method relies on the FileReader API, so it won't work on IE9 as you've pointed out, but I don't think it is possible otherwise.
At the end of the day, do you need IE9 compatibility ? You might find it acceptable to add a functionality that works for all but a few percent of your user base.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top