3

I want display the photo select using input file dialog but this code does not seem to execute and not display any error:

var Box = $('.UploadBox');
var Image = $('.Image');
var Input = $('.UloadBox .File');
Box.hide()
$('.Photo .Upload').click(function () {
    Box.show();
    Input.change(function () {
        var File = this.files[0];
        var Reader = new FileReader();
        Reader.onload = function (e) {
            Image.attr('src', e.target.result);
        };
        Reader.readAsDataURL(this.files[0]);
    });
});
1
  • 1
    Start by writing to console to see if the file exists: console.log(this.files[0]); Commented May 6, 2015 at 0:17

1 Answer 1

1

This is a solution that I use. It handles the upload of multiple images. If you only wish to provide the option to upload one image at a time, then you can simply change the HTML for the input element. For either of these inputs, the javascript I provided runs results in the same execution. Then it becomes a matter of you limiting your file upload to one or many files.

For multiple files: <input type="file" id="files" name="files[]" multiple />
For one single file: <input type="file" id="files" name="file" />

var numDocuments = 0;
var numDocumentsProcessed = 0;

function processFiles() {
  numDocuments = files.length;
  for (var i = 0, f; f = files[i]; i++) {
    var fileReader = new FileReader();
    fileReader.onloadend = (function (file) {
      return function (evt) {
        doSomethingWithFile(evt, file)
      }
    })(f);
    fileReader.readAsDataURL(f);
  }
}

function onFilesSelected(event) {
  files = event.target.files; // FileList object
  processFiles();
}

function doSomethingWithFile(evt, file) {
  var key = file.name;
  var value = evt.target.result;
  var container = document.getElementById('image-container');
  var image = document.createElement('img');
  image.src = evt.target.result;
  container.appendChild(image);
  if (++numDocumentsProcessed === numDocuments) {
    //final steps after final image processed
  }
}

document.getElementById('files').addEventListener('change', onFilesSelected, false);
<input type="file" id="files" name="files[]" multiple />
<br>
<div id="image-container"></div>

Sign up to request clarification or add additional context in comments.

1 Comment

In spite of your title, I actually did this without JQuery. I hope you can still use it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.