Халид Хан
Халид Хан

Reputation: 57

Using jQuery to View a File Before Upload

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]);
    });
});

Upvotes: 3

Views: 604

Answers (1)

ThisClark
ThisClark

Reputation: 14823

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>

Upvotes: 1

Related Questions