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 with over 11 years of Vue development experience since 2014, 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 Use JavaScript setTimeout()
How to Use JavaScript setTimeout()

How to sleep in Javascript
How to sleep in Javascript

What are the three dots `...` in JavaScript do?
What are the three dots `...` in JavaScript do?

How to Disable Right Click on a Website Using JavaScript
How to Disable Right Click on a Website Using JavaScript

Answers by CoreUI Core Team