1

I have tried to convert an image from file input in vue, I'm not so sure I did it in the proper way. What I want to achieve is to get the Image url, assign it to a data variable and push it into my mongoose DB

That's what I tried based on a guide I read:

Input:

    <div class="singleInput50">
      <span>Personal Image:</span>
      <input type="file" @change="handleImage" accept="image/*">
    </div>

HandleImage:

handleImage(e) {
      const selectedImage = e.target.files[0];
      this.createBase64Image(selectedImage);
    },

createBase64Image:

createBase64Image(fileObject) {
  const reader = new FileReader();

  reader.onload = (e) => {
    this.userObject.imgPersonal = e.target.result;
  };
  reader.readAsBinaryString(fileObject)
  console.log("file object", fileObject);
}

ImgPersonal value after the functions has been executed:

imgPersonal:"ÿØÿàJFIFÿÛC\n \n  \n$ &%# #"(-90(*6+"#2D26;=@@@&0FKE>J9?@=ÿÛC =)#)==================================================ÿÀ"ÿÄ \nÿĵ}!1AQa"q2¡#B±ÁRÑð$3br \n%&'()*456789:CDEFGH

I have tried also with readAsDataURL(), seems like the same outcome

Any suggestions?

1 Answer 1

1

I'm using this function to convert files to base64. Works fine for me:

export default function (blob) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onerror = reject
    reader.onload = () => {
      resolve(reader.result)
    }
    reader.readAsDataURL(blob)
  })
}

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

1 Comment

Actually That was my mistake and it's seems to work just fine. Thanks for the answer I'll approve 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.