How to upload multiple images as an array in vue.js?

Member

by lizzie , in category: Javascript , 6 months ago

How to upload multiple images as an array in vue.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by denis , 4 months ago

@lizzie 

To upload multiple images as an array in Vue.js, you can follow these steps:

  1. Define an empty array in the data section of your Vue component to store the selected images:
1
2
3
4
5
data() {
  return {
    selectedImages: [],
  };
}


  1. In your template, include an element to allow users to select multiple images:
1
<input type="file" multiple @change="handleImageUpload" />


  1. Define a method called handleImageUpload to handle the image selection. Access the selected files using event.target.files and convert it into an array using the Array.from() method. Then, push each image file into the selectedImages array:
1
2
3
4
5
6
methods: {
  handleImageUpload(event) {
    const selectedFiles = Array.from(event.target.files);
    selectedFiles.forEach(file => this.selectedImages.push(file));
  }
}


  1. If you want to display the selected images, you can use the v-for directive to iterate over the selectedImages array. For each image, use the URL.createObjectURL() method to generate a temporary URL for that image and render it using an tag:
1
2
3
<div>
  <img v-for="image in selectedImages" :src="URL.createObjectURL(image)" :key="image.name" />
</div>


Note: Remember to clean up the temporary URLs generated by URL.createObjectURL() when the component is destroyed to prevent memory leaks. You can do this by creating an beforeDestroy lifecycle hook and calling URL.revokeObjectURL() for each image in the selectedImages array.