article

Friday, March 11, 2022

Vuejs Vue CLI File Upload with Axios and PHP

Vuejs Vue CLI File Upload with Axios and PHP

Install vue-axios
npm install --save axios vue-axios
https://www.npmjs.com/package/vue-axios

C:\vuejs\myapp>npm install --save axios vue-axios
C:\vuejs\myapp>npm run serve
src/main.js
//src/main.js
import { createApp } from 'vue'
import App from './App.vue'

import axios from 'axios' // C:\vuejs\myapp>npm install --save axios vue-axios

import VueAxios from 'vue-axios'


createApp(App).use(VueAxios, axios).mount('#app')
src/components/fileUpload.vue
//src/components/fileUpload.vue
<template>
  <div class="container">
    <div class="row">
      <h1>Vuejs Vue CLI File Upload with Axios and PHP</h1>
      <label>File
        <input type="file" id="file" ref="file"/>
      </label>
        <button v-on:click="uploadFile()">Upload</button>
    </div>
  </div>
</template>

<script>

  export default  {   
      data () {
      return {          
          file:''
      }    
    },
    methods: {     

            uploadFile: function(){

                 this.file = this.$refs.file.files[0];                  
                 let formData = new FormData();
                 formData.append('file', this.file);
                 this.$refs.file.value = '';
                this.axios.post('http://localhost/devtest/upload.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);
                 });

            }
    },
    
}
</script>
src/App.vue
//src/App.vue
<template>
  <div id="app">
      <FileUpload/>
  </div>
</template>
<script>
import FileUpload from './components/fileUpload.vue'
 
      export default {
                 name: 'app',
                       components: {
                             FileUpload
                }
       }
</script>
upload.php
//upload.php
<?php  
    header('Access-Control-Allow-Origin: *');  
     $filename = $_FILES['file']['name'];
     $allowed_extensions = array('jpg','jpeg','png','pdf');
      $extension = pathinfo($filename, PATHINFO_EXTENSION);
       if(in_array(strtolower($extension),$allowed_extensions) ) {     
          if(move_uploaded_file($_FILES['file']['tmp_name'], "upload/".$filename)){
                echo 1;
          }else{
              echo 0;
          }
    }else{
        echo 0;
    } 
?>

Related Post