File Upload Made Easy in Vue.js: A Frontend Guide

A guide on managing a file upload component along with a preview
Nov 7 2023 · 6 min read

Background

In today’s web applications, users have come to expect a seamless and intuitive file upload experience, but for developers,  implementing this functionality can be a complex task. Handling different file types, and sizes, and providing user-friendly previews are just a few of the challenges. 

In this blog post, we will introduce you to web-file-upload a powerful file upload library designed to simplify and enhance the file upload experience for VueJs and React. With “@canopassoftware/vue-file-upload you can create a polished and user-friendly file upload component with ease.

We’ll take you through the installation process, customization options, and styling tips to help you integrate this library into your Vue.js project. Whether you’re a seasoned Vue.js developer or just starting out, this tutorial will empower you to provide your users with an exceptional file upload experience.

Let’s get started!

What we’ll implement in this blog?

Sponsored

Balance is not something you find; it's something you create.

Justly helps you strike that perfect work-life balance, making room for your health and happiness.

Use Cases and Features

The library offers several use cases and features that can enhance the file upload experience in your Vue.js project. Here are some of the notable use cases and features of the library:

1. Get a callback after each file upload:

You can use the library to manage post-upload functionality using callbacks.

For example,

  • You want to show a message on a successful file upload
  • You can save file information to a database
  • You want to send notifications to users upon successful file uploads
  • You want to show progress while uploading the files

2. Separate different files using appropriate icons:

  • The library can automatically display file icons based on the file type. This feature makes it easier for users to identify their uploaded files, as different file types can be represented by corresponding icons.

For example,

Screenshot from 2023-11-06 18-47-48.png

3. Preview of Images, Videos, and GIFs:

  • The library includes built-in support for previewing images, videos, and GIFs. When a user uploads a file of these types, the component can display a thumbnail or preview of the content, allowing users to confirm their uploads.

4. File Type Validation:

  • The library allows you to specify accepted file types and validate files before uploading. You can define which file formats are allowed, ensuring that only valid files are uploaded.

5. Progress Indicators:

  • The library provides progress indicators during file uploads. Users can see the progress of the file being uploaded, which improves the overall user experience and transparency.

6. Customization Options:

  • The library offers various customization options, allowing you to tailor the file upload component to your project’s specific design and functionality requirements. You can adjust the appearance, and behavior to match your application’s needs.

7. User-Friendly User Interface:

  • The library offers a user-friendly and intuitive interface for selecting and uploading files. Users can easily interact with the component to add and manage their files.

Also, it has provided a Vue project with implementation. so, you can use or refer to it directly.

Prerequisites

Before we dive into the implementation, make sure you have the following prerequisites in place:

  1. A Vue.js project set up.
  2. Basic knowledge of Vue.js props, events, HTML, and CSS.

Installation

To get started, you need to install the @canopassoftware/vue-file-upload library. You can do this using either npm or yarn:

> npm install @canopassoftware/vue-file-upload
# or
> yarn add @canopassoftware/vue-file-upload

Register a component

This library has two components to manage file upload:

1. SingleFileUpload

2. MultipleFileUpload

Approach 1: Using app.component in the main entry file

In this approach, we need to declare and register the components directly in your main entry file (usually main.js or main.ts) using the app.component method.

Here's how it works:

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'

// import components from library
import { SingleFileUpload, MultipleFileUpload } from '@canopassoftware/vue-file-upload'
import "@canopassoftware/vue-file-upload/style.css" // import css

const app = createApp(App)

// declare components for your project
app.component('SingleFileUpload', SingleFileUpload)
app.component('MultipleFileUpload', MultipleFileUpload)

app.use(router)

app.mount('#app')
  • Here, we are importing two components, SingleFileUpload and MultipleFileUpload, from the library. These components are provided by the library and can be used to create file upload features in your application.
  • Registers the components from the library under the name SingleFileUpload and MultipleFileUpload in your Vue application. You can use this component in your templates by referencing it as <SingleFileUpload /> and <MultipleFileUpload />.

Approach 2: Using the components option in a Vue file

In this approach, you import and declare the components within a specific Vue file or component where you intend to use them. This is typically done in a .vue file or a script block within a component file.

Here's how it works:

<script lang="ts">
// import components from library
import { SingleFileUpload, MultipleFileUpload } from '@canopassoftware/vue-file-upload'
import "@canopassoftware/vue-file-upload/style.css" // import css

export default {
  name: 'IndexView',
  components: {
    SingleFileUpload,    
    MultipleFileUpload
  },
}
</script>
  • This is a more scoped approach, as the components are only available within the scope of the component where they are declared.

Use Single File Upload Component

Using this component we can easily manage add/update file uploading.

Vue component

<div class="flex flex-wrap">
   <SingleFileUpload
      :uploadBtn="'Upload'"
      :progressBtn="'Uploading...'"
      :uploadedFile="uploadedFile"
      :callback="handleFileUploading"
    >
      <template v-slot="file">
        <!-- add your design or use from library examples -->
     </template>
   </SingleFileUpload>
</div>
  • In this code, you create a file upload component using the SingleFileUpload component provided by the library.

You pass several props to customize the behavior of the component:

  • :uploadBtn="'Upload'": Sets the text for the upload button to "Upload."
  • :progressBtn="'Uploading...'": Defines the text displayed on the button during the file upload process.
  • :uploadedFile="uploadedFile": Binds the uploadedFile data property to receive information about the uploaded file.
  • :callback="handleFileUploading": Binds an async handleFileUploading method for uploading files and showing the progress while uploading the file.

Vue component script

<script lang="ts">
export default {
  name: 'IndexView',
  data() {
    return {
      uploadedFile: {} as {
        fileType: string
        fileUrl: string
        fileName: string
      }
    }
  },
  methods: {
    async handleFileUploading(file: any) {
      // add your fileuploading logic to server and set data to the uploadedFile
      this.uploadedFile.fileType = 'image' // uploaded file type
      this.uploadedFile.fileUrl = 'https://picsum.photos/300/224' // uploaded file url
      this.uploadedFile.fileName = file.name // uploaded file name

      await new Promise((resolve) => setTimeout(resolve, 2000))
    },
  }
}
</script>

In the data function, you define the data properties used within the component:

  • uploadedFile: An object that will hold information about the uploaded file, such as its type, URL, and name.
  • An async handleFileUploading method handles the uploading process of the file. With this method, the library component will handle whether a file is currently being uploaded.

Awesome!!👌we are done with the single file upload implementation.

Use Multiple File Upload Component

Using this component we can easily manage add/update files and show the preview of all the files before uploading.

Vue component

<div class="flex flex-wrap">
    <MultipleFileUpload
      :removeBtn="'remove'"
      :uploadBtn="'Upload'"
      :progressBtn="'Uploading...'"
      :uploadedFiles="uploadedFiles"
      :callback="handleFilesUploading"
    >
      <template v-slot="file">
        <!-- add your design or use from library examples -->
      </template>
    </MultipleFileUpload>
</div>

In this code, you create a file upload component using the MultipleFileUpload component provided by the library.

You pass several props to customize the behavior of the component:

  • :removeBtn="'remove'": Sets the text for the button to remove selected or already uploaded files.
  • :uploadBtn="'Upload'": Sets the text for the button.
  • :progressBtn="'Uploading...'": Defines the text displayed on the button during the file upload process.
  • :uploadedFiles="uploadedFiles": Binds this data property to store information about the uploaded files.
  • :callback="handleFilesUploading": Binds an async handleFilesUploading method for uploading files and showing the progress while uploading the files.

Vue component script

<script lang="ts">
export default {
  name: 'IndexView',
  data() {
    return {
      uploadedFiles: [] as Array<{
        fileType: string
        fileUrl: string
        fileName: string
      }>
    }
  },
  methods: {
    async handleFilesUploading(files: any) {
      this.uploadedFiles = []

      // add your fileuploading logic to server and set data to the uploadedFiles
      for (var i = 0; i < files.length; i++) {
        this.uploadedFiles.push({
          fileType: 'image', // uploaded file type
          fileUrl: 'https://picsum.photos/300/224', // uploaded file url
          fileName: 'example-image.jpg' // uploaded file name
        })
      }

      await new Promise((resolve) => setTimeout(resolve, 2000))
    }
  }
}
</script>

In the data function, you define the data properties used within the component:

  • uploadedFiles: An array that will hold information about the uploaded files, where each file is represented as an object with properties for type, URL, and name.
  • An async handleFilesUploading method handles the uploading process of the file. With this method, the library component will handle whether a file is currently being uploaded.

𝐓𝐚-𝐝𝐚!! 🎉 we have completed the multiple file upload component implementation.

Conclusion

By following this guide, you’ve learned how to integrate @canopassoftware/vue-file-upload into your Vue.js project, allowing you to create a file upload component that is not only functional but also visually appealing. You can customize it to match your project’s design, and file type restrictions.

As you continue to build and improve your web applications, remember that a great file upload experience can make a significant difference in user satisfaction and engagement. With @canopassoftware/vue-file-upload at your disposal, you have the tools to provide your users with a top-tier file-uploading experience.

We encourage you to explore the library further, experiment with its features, and adapt it to your unique project requirements. Suggestions are most welcome, and if you have any doubts then drop them into the library.

We hope this guide can help build your web applications.

Thanks for reading!! 👋👋👋

Similar Articles


dharti-r image
Dharti Ramoliya
Web developer at canopas | Eager to Elevate Your Web Experience


dharti-r image
Dharti Ramoliya
Web developer at canopas | Eager to Elevate Your Web Experience

background-image

Get started today

Let's build the next
big thing!

Let's improve your business's digital strategy and implement robust mobile apps to achieve your business objectives. Schedule Your Free Consultation Now.

Get Free Consultation
footer
Subscribe Here!
Follow us on
2024 Canopas Software LLP. All rights reserved.