1

I have two input files fields in a form, as followed:

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

    <div class="singleInput50">
      <span>Business logo</span>
      <input type="file" @change="handleImage" accept="image/*" id="businessLogo">
    </div>

Both designated to hold a different image(that would convert to base64 after that) and should be binded to a different data variable, like this two:

businessLogo: '',
imgPersonal: '',

Both handled with this methods:

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

      reader.onload = (e) => {
        this.userObject.imgPersonal = e.target.result; **//Here I can't figure out how to make it dynamic, if a user choosed personalImage or businessLogo field**
      };
      reader.readAsDataURL(fileObject)
      // console.log("file object", fileObject);
    },

The goal is to make assigning dynamic. if the user will upload a file to "personal image" input the image will be assigned to "imgPersonal" data variable, and if to "business Logo" the image image will be assigned to "business Logo"

1 Answer 1

1

You can simply pass an argument to your methods:

handleImage(e, imageName) {
      const selectedImage = e.target.files[0];
      this.createBase64Image(selectedImage, imageName);
},
createBase64Image(fileObject, imageName) {
      const reader = new FileReader();

      reader.onload = (e) => {
        this.userObject[imageName] = e.target.result; **//Here I can't figure out how to make it dynamic, if a user choosed personalImage or businessLogo field**
      };
      reader.readAsDataURL(fileObject)
      // console.log("file object", fileObject);
},

An in your template:

<div class="singleInput50">
      <span>Personal Image:</span>
      <input type="file" @change="handleImage($event, 'imgPersonal')" accept="image/*" ref="imgPersonal">
</div>

<div class="singleInput50">
      <span>Business logo</span>
      <input type="file" @change="handleImage($event, 'businessLogo')" accept="image/*" id="businessLogo">
</div>
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.