One data grid for JavaScript, React, Vue & Angular. Sorting, filtering, virtualization, pinning, and CSV export included. Early access $199 $349 → [Get it now]

How to upload files in Vue

Handling file uploads is a common requirement in modern Vue applications, from profile pictures to document management systems. As the creator of CoreUI, I’ve implemented file upload functionality in countless production applications. The most effective solution is to use a file input element with a change event handler and FormData to send files to your server. This approach works seamlessly with any backend API.

Use a file input with @change event and FormData to upload files in Vue 3.

<template>
  <div>
    <input type='file' @change='handleFileUpload' />
    <button @click='uploadFile'>Upload</button>
  </div>
</template>

<script>
import { ref } from 'vue'

export default {
  setup() {
    const selectedFile = ref(null)

    const handleFileUpload = (event) => {
      selectedFile.value = event.target.files[0]
    }

    const uploadFile = async () => {
      if (!selectedFile.value) return

      const formData = new FormData()
      formData.append('file', selectedFile.value)

      const response = await fetch('/api/upload', {
        method: 'POST',
        body: formData
      })

      const result = await response.json()
      console.log('Upload success:', result)
    }

    return { handleFileUpload, uploadFile }
  }
}
</script>

The file input’s change event provides access to selected files through event.target.files. The first file is stored in a ref variable. When uploading, FormData creates a multipart/form-data request that servers expect for file uploads. The append() method adds the file with a field name that matches your API’s expectations. The fetch API sends the FormData directly as the request body.

Best Practice Note

This is the same reliable file upload pattern we use in CoreUI Vue components. For better user experience, add file type validation, size limits, and upload progress indicators. Consider using Axios interceptors for consistent error handling across all file uploads in your application.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.
How to declare the optional function parameters in JavaScript?
How to declare the optional function parameters in JavaScript?

How to Merge Objects in JavaScript
How to Merge Objects in JavaScript

How to round a number to two decimal places in JavaScript
How to round a number to two decimal places in JavaScript

How to check if a string is a number in JavaScript
How to check if a string is a number in JavaScript