1

There's an example from MDN on how to use FileReader to show a preview image:

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

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

    var img = document.createElement("img");
    img.classList.add("obj");
    img.file = file;
    preview.appendChild(img); // Assuming that "preview" is the div output where the content will be displayed.

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

I'm wondering how to use this in a Vue component. It seems to me the asynchronous part isn't that easy to handle, but I'm new to Vue, and maybe that's an advanced feature.

1 Answer 1

1

Create a component with an <img :src="src" id="img> tag and src property in it's data object. You could pass an idx prop from parent component along with a file if you would like to make a gallery and and it to an img id, because as we reference an image by id we need unique id for each img element.

Create a method loadPicture

loadPicture(file) {
   let self = this;
   let img = document.getElementById('img');
   var reader = new FileReader();
   reader.onload = function(e) {
     self.src = e.target.result;
   }
   reader.readAsDataURL(file);
}`

Then call this method in mounted lifecycle

mounted() {
     this.loadPicture();
}

Working example: https://jsfiddle.net/8dnhh23o/
Multiple images example: https://jsfiddle.net/o1037uks/

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

Comments

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.