Courses

Vue.js 3 + Laravel 11 + Vite: SPA CRUD

File Upload Example

Summary of this lesson:
- Implementing file upload functionality
- Handling FormData for file submissions
- Managing file input events in Vue
- Setting up basic file processing in Laravel

In this lesson, let's see how we can upload files using Vue.js. It's a pretty complex topic because it isn't just adding a new field. Let's see how we can do that.

vue file upload


Vue: File Upload Input

First, let's add a new file upload field and call it thumbnail.

resources/js/components/Posts/Create.vue:

<template>
<form @submit.prevent="storePost(post)">
// ...
 
<!-- Thumbnail -->
<div class="mt-4">
<label for="thumbnail" class="block font-medium text-sm text-gray-700">
Thumbnail
</label>
<input @change="post.thumbnail = $event.target.files[0]" type="file" id="thumbnail" />
<div class="text-red-600 mt-1">
<div v-for="message in validationErrors?.thumbnail">
{{ message }}
</div>
</div>
</div>
 
<!-- Buttons -->
<div class="mt-4">
<button :disabled="isLoading" class="inline-flex items-center rounded-md bg-indigo-600 px-3 py-2 text-sm uppercase text-white disabled:opacity-75 disabled:cursor-not-allowed">
<span v-show="isLoading" class="inline-block animate-spin w-4 h-4 mr-2 border-t-2 border-t-white border-r-2 border-r-white border-b-2 border-b-white border-l-2 border-l-blue-600 rounded-full"></span>
<span v-if="isLoading">Processing...</span>
<span v-else>Save</span>
</button>
</div>
</form>
</template>
 
<script setup>
// ...
const post = reactive({
title: '',
content: '',
category_id: '',
thumbnail: ''
})
// ...
</script>

The problem with the file input is that we cannot use v-model="thumbnail". As you can see instead of v-model we used @change="post.thumbnail = $event.target.files[0]". So what does it mean?

We listen for a change on the input file and then manually...

The full lesson is only for Premium Members.
Want to access all 27 lessons of this course? (115 min read)

You also get:

  • 69 courses (majority in latest Laravel 11)
  • Premium tutorials
  • Access to repositories
  • Private Discord