Elevate Your Vue 3 App Image Upload with Preview and API Integration

Spread the love

Vue 3: Developers may create dynamic web apps using Vue 3, a powerful JavaScript framework. In this in-depth article, we’ll look at how to provide image upload and preview features in a Vue 3 application.

Step 1: Create a New Vue 3 App

To begin, create a new Vue 3 application. Launch your terminal and type the following command:

vue create vue-image-upload-preview

This command creates a new Vue 3 project called "vue-image-upload-preview".

Step 2: Navigate to Your Vue 3 App

To easily access and manage your Vue 3 project files, use the terminal to go to its root directory:

cd vue-image-upload-preview

Step 3: Develop the Image Preview Component with Vue 3 (Composition API)

In this lesson, we’ll use the Vue 3 Composition API to create a specific component for previewing images before uploading them. Create a new component called 'FilePreview.vue' in the '/src/components' directory. The following code demonstrates the process:

<template>
  <div>
    <div
      class="imagePreviewWrapper"
      :style="{ 'background-image': `url(${previewImage})` }"
      @click="selectImage"
    ></div>

    <input
      ref="fileInput"
      type="file"
      @input="pickFile"
    />

    <button @click="uploadImage" :disabled="!previewImage">Upload Image</button>
  </div>
</template>

<script setup>
import { ref } from 'vue';

const previewImage = ref(null);
const isUploading = ref(false);

const selectImage = () => {
  fileInputRef.value.click();
};

const fileInputRef = ref(null);

const pickFile = () => {
  const input = fileInputRef.value;
  const file = input.files[0];

  if (file) {
    const reader = new FileReader();
    reader.onload = (e) => {
      previewImage.value = e.target.result;
    };
    reader.readAsDataURL(file);
  }
};

const uploadImage = async () => {
  if (previewImage.value) {
    isUploading.value = true;

    // Simulate a POST request to an imaginary API
    try {
      const response = await fetch('api/image', {
        method: 'POST',
        body: JSON.stringify({ image: previewImage.value }),
        headers: {
          'Content-Type': 'application/json',
        },
      });

      if (response.ok) {
        // Image successfully uploaded
        alert('Image uploaded successfully!');
      } else {
        // Handle error
        alert('Image upload failed. Please try again.');
      }
    } catch (error) {
      // Handle network or other errors
      alert('An error occurred while uploading the image.');
    }

    isUploading.value = false;
  }
};
</script>

<style scoped lang="scss">
.imagePreviewWrapper {
  width: 250px;
  height: 250px;
  display: block;
  cursor: pointer;
  margin: 0 auto 30px;
  background-size: cover;
  background-position: center center;
}

button {
  margin-top: 10px;
  padding: 10px 20px;
  background-color: #007bff;
  color: #fff;
  border: none;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}
</style>

This code adheres to the Composition API guidelines of Vue 3, resulting in a clean and efficient code structure.

Step 3: Develop the Image Preview Component with Vue 3 (Options API)

In this step, we’ll create the same component for displaying image previews before uploading using the Vue 3 Options API. Create a new component called 'FilePreview.vue' in the '/src/components' directory. The following code demonstrates the process:

<template>
  <div>
    <div
      class="imagePreviewWrapper"
      :style="{ 'background-image': `url(${previewImage})` }"
      @click="selectImage"
    ></div>

    <input
      ref="fileInput"
      type="file"
      @input="pickFile"
    />

    <button @click="uploadImage" :disabled="!previewImage">Upload Image</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      previewImage: null,
      isUploading: false,
    };
  },
  methods: {
    selectImage() {
      this.$refs.fileInput.click();
    },
    pickFile() {
      const input = this.$refs.fileInput;
      const file = input.files[0];
      if (file) {
        const reader = new FileReader();
        reader.onload = (e) => {
          this.previewImage = e.target.result;
        };
        reader.readAsDataURL(file);
      }
    },
    async uploadImage() {
      if (this.previewImage) {
        this.isUploading = true;

        // Simulate a POST request to an imaginary API
        try {
          const response = await fetch('api/image', {
            method: 'POST',
            body: JSON.stringify({ image: this.previewImage }),
            headers: {
              'Content-Type': 'application/json',
            },
          });

          if (response.ok) {
            // Image successfully uploaded
            alert('Image uploaded successfully!');
          } else {
            // Handle error
            alert('Image upload failed. Please try again.');
          }
        } catch (error) {
          // Handle network or other errors
          alert('An error occurred while uploading the image.');
        }

        this.isUploading = false;
      }
    },
  },
};
</script>

<style scoped lang="scss">
.imagePreviewWrapper {
  width: 250px;
  height: 250px;
  display: block;
  cursor: pointer;
  margin: 0 auto 30px;
  background-size: cover;
  background-position: center center;
}

button {
  margin-top: 10px;
  padding: 10px 20px;
  background-color: #007bff;
  color: #fff;
  border: none;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}
</style>

Step 4: Incorporate the Component into App.vue (Composition API)

To incorporate your image preview component into your Vue 3 application effortlessly, navigate to the '/src/' directory and open the 'App.vue' file. To include the FilePreview component, add the following code:

<template>
  <FilePreview></FilePreview>
</template>
 
<script>
import FilePreview from './components/FilePreview';
</script>

Step 4: Incorporate the Component into App.vue (Options API)

In this case, we’ll use the Vue 3 Options API to accomplish the same thing. Navigate to the '/src/' directory and double-click the 'App.vue' file. To include the FilePreview component, add the following code:

<template>
  <FilePreview></FilePreview>
</template>
 
<script>
import FilePreview from './components/FilePreview';
 
export default {
  components: {
    FilePreview
  }
}
</script>

Step 5 – Conclusion

Congratulations! In your Vue.js application, you have successfully integrated image upload with a preview functionality. Before posting, users can now select images and watch a preview. Vue.js makes it simple to construct dynamic and interactive web application components that improve the user experience.

In conclusion, this lesson walked you through the following steps:

  1. Make a new Vue.js application.
  2. Navigating to the root directory of the Vue.js app.
  3. Putting together an image preview component.
  4. The component is being added to the main App.vue file.

You’ve learnt how to utilize Vue.js to add a user-friendly image upload and preview capability to your online applications.

If you are looking for an API which handles the image Upload. I have written an article “Mastering File Uploads in Laravel 10 Validation and Database Storage” where I ‘ve explained in detailed how to handle image uploads in Laravel 10

Have fun coding!