How to upload file with Vue.js and PHP

File upload is one of the basic requirements on the web application.

I am using the Axios package to send AJAX request to upload a fil. Send a selected file using the FormData object.

In this tutorial, I show how you can upload a file using Vue.js and PHP.

1. Download & Include

  • Download Axios package from GitHub. or you can also use CDN (
  • Now, include axios.min.js with vue.js in the <head>section.
<script src="vue.js"></script>
<script src=""></script>


Create a file element and a button in the <div id='myapp'>.

In the file element added ref='file' which use to get the selected file in Vue script.

Add @click event on the button which calls uploadFile() method.

Completed Code

<div id='myapp'> <input type="file" id="file" ref="file" /> <button type="button" @click='uploadFile()' >Upload file</button>

3. PHP

Create an ajaxfile.php file and uploads directory for storing the files.

Assign valid file extensions in $valid_extensions Array and get the file extension from the file.

Upload the file if a file extension is found in $valid_extension Array and return 1 otherwise 0.

Completed Code

<?php // File name
$filename = $_FILES['file']['name']; // Valid file extensions
$valid_extensions = array("jpg","jpeg","png","pdf"); // File extension
$extension = pathinfo($filename, PATHINFO_EXTENSION); // Check extension
if(in_array(strtolower($extension),$valid_extensions) ) { // Upload file if(move_uploaded_file($_FILES['file']['tmp_name'], "uploads/".$filename)){ echo 1; }else{ echo 0; }
}else{ echo 0;
} exit;

4. Script

Initialize Vue on #myapp.

Add file data variable and define uploadFile() method which gets called on the upload button click.

Select the file and append in FormData object.

Send POST request to ajaxfile.php and pass formData as data.

Also, set Content-Type: 'multipart/form-data' in header.

On successful callback if is 0 then alert('File not uploaded.') otherwise, alert('File uploaded successfully.').

Completed Code

var app = new Vue({ el: '#myapp', data: { file: "", }, methods: { uploadFile: function(){ this.file = this.$refs.file.files[0]; let formData = new FormData(); formData.append('file', this.file);'ajaxfile.php', formData, { headers: { 'Content-Type': 'multipart/form-data' } }) .then(function (response) { if(!{ alert('File not uploaded.'); }else{ alert('File uploaded successfully.'); } }) .catch(function (error) { console.log(error); }); } }

5. Conclusion

You don’t need to create a <form > to add file element.

You can pass the extra parameter to FormData object using append() method which you required for processing in AJAX file.

Related Posts