Home > Software design >  Retrieve png file and render it for preview
Retrieve png file and render it for preview

Time:07-23

So I have an img tag in my template that is bound to a state "imageBuffer"

 <img v-bind:src="imageBuffer" alt="" />

and I have the following logic, the page has two file inputs and I used this one function to handle all file picking:

onFilePicked(event, type) {
      const extension = this.getExtension(event.target.files[0].name);
      let isValid = false;

      if (type === 'pdf' && extension === 'pdf') {
        isValid = true;
      }

      if (type === 'image' && (extension === 'jpg' || extension === 'png')) {
        isValid = true;
      }

      if (isValid) {
        const fileReader = new FileReader();
        if (type === 'pdf') {
          const files = event.target.files;
          let filename = files[0].name;
          fileReader.addEventListener('load', () => {
        });

          this.pdf = files[0];


        } else if (extension === 'png' || extension === 'jpg') {

          fileReader.addEventListener('load', () => {
            this.imageBuffer = fileReader.readAsDataURL(event.target.files[0]);
          });

        }
      } else {
        alert('Invalid file type');
      }
    },

The PDF chooser is working fine however when I console.log the "imagebuffer" it doesn't seem to work and it's not rendering the image preview. Which function should I use from FileReader to retrieve the image buffer and convert it into a png?

CodePudding user response:

Your file reader's load event will never be triggered because you didn't tell it to read anything.

See the method readAsDataURL. They even have a decent example of usage on that page


You need to re-arrange your code a little bit

fileReader.addEventListener('load', () => {
    // imageBuffer is now our dataURL from the file uploaded
    this.imageBuffer = fileReader.result;
});
// load the file the user selected
fileReader.readAsDataURL(event.target.files[0]);
  • Related