How to upload file with Vue.js and PHP

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

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

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

How to upload file with Vue.js and PHP


Contents

  1. Download & Include
  2. HTML
  3. PHP
  4. Script
  5. Output
  6. Conclusion

1. Download & Include

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

2. HTML

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>
</div>

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 response.data 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);

       axios.post('ajaxfile.php', formData,
       {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
       })
       .then(function (response) {

          if(!response.data){
             alert('File not uploaded.');
          }else{
             alert('File uploaded successfully.');
          }

       })
       .catch(function (error) {
           console.log(error);
       });

     }
   }
})

5. Output


6. 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.

View this tutorial to know multiple files upload using Vue.js and PHP.

If you found this tutorial helpful then don't forget to share.