Thursday, 30 April 2020

Vue js File Upload with PHP & Axios



This post will guide you to How to upload files using Vue.js with PHP script and Axios package. This post will help your to uploading files with VueJS with Axios. As a programmer we have already know file upload is one or the basic feature which has been required in any web based application for store or upload file on server. In this post, we will use Vue.js library & Axios package as front end technology and PHP will be use as back end technology for upload files on server.

For upload file, here we have use Axios package with Vue.js library, by using this Axios package we will send Ajax request for upload file. For send selected file here we have use FormData object, which will send file via Ajax request to PHP script. Do you know Vue.js and Axios package is work together for send HTTP requests. But here we want to send file via Ajax request for Uploading and it is little bit challenging task, because here we have to use Axios package for send file to PHP script. For this here we have use FormData() object for send selected file to PHP script via Ajax request. This tutorial will provide you simple and quick guide for handle file upload process in VueJS with PHP script.







First we have to import Vue.js and Axios package in our working index page. For this you can see below code in which we have import VueJS library and Axios package link at the header of file.


<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>


First in Vue application, we have to define element for Vue appliction. For this we have to define in any tag with id="uploadApp" This attribute value will be used in the property of el: which binds the new Vue object to HTML tag with id="uploadApp".


<div class="container" id="uploadApp">

</div>


After for display upload file validation error and success message, here we have use Bootstrap alert class. Within Bootstrap alert class we have use v-if directive for display alert message on condition. If this v-if directive value is equal to true then it will display validation error or success message on web page, otherwise it will be hide from web page. Same way for display dynamic error or success message, here we have use double braces {{ }} as place-holders for data. This data value will be define on different event.


<div class="container" id="uploadApp">
   <br />
   <h3 align="center">How to upload file using Vue.js with PHP</h3>
   <br />
   <div v-if="successAlert" class="alert alert-success alert-dismissible">
    <a href="#" class="close" aria-label="close" @click="successAlert=false">&times;</a>
    {{ successMessage }}
   </div>

   <div v-if="errorAlert" class="alert alert-danger alert-dismissible">
    <a href="#" class="close" aria-label="close" @click="errorAlert=false">&times;</a>
    {{ errorMessage }}
   </div>
</div>


After this we have to create input file tag for select image or file from local computer. In input file tag we have use ref='file' which will be used for get the selected file in Vue Script.

Once file has been selected then for upload file on server, here we have define one button tag. In that button we have define @click directive. So when we have click on button, then it will called uploadImage() function.

After uploading of image, now we want to display on web page. So here we have create on div tag and under that tag we have use v-html directive. This directive is used to display HTML code under that tag.


<!DOCTYPE html>
<html>
 <head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>How to upload file using Vue.js with PHP</title>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  
 </head>
 <body>
  <div class="container" id="uploadApp">
   <br />
   <h3 align="center">How to upload file using Vue.js with PHP</h3>
   <br />
   <div v-if="successAlert" class="alert alert-success alert-dismissible">
    <a href="#" class="close" aria-label="close" @click="successAlert=false">&times;</a>
    {{ successMessage }}
   </div>

   <div v-if="errorAlert" class="alert alert-danger alert-dismissible">
    <a href="#" class="close" aria-label="close" @click="errorAlert=false">&times;</a>
    {{ errorMessage }}
   </div>
   <div class="panel panel-default">
    <div class="panel-heading">
     <div class="row">
      <div class="col-md-6">
       <h3 class="panel-title">Upload File</h3>
      </div>
      <div class="col-md-6" align="right">
       
      </div>
     </div>
    </div>
    <div class="panel-body">
     <div class="row">
      <div class="col-md-4" align="right">
       <label>Select Image</label>
      </div>
      <div class="col-md-4">
       <input type="file" ref="file" />
      </div>
      <div class="col-md-4">
       <button type="button" @click="uploadImage" class="btn btn-primary">Upload Image</button>
      </div>
     </div>
     <br />
     <br />
     <div v-html="uploadedImage" align="center"></div>
    </div>
   </div>
  </div>
 </body>
</html>





So, here our HTML code part is ready, now we have go to Vue.js code part. In this part, Vue JS has been initialize on #uploadApp.

After this, we have to define data for Vue.js application, here we have to define file variable with blank value, successAlert with false value for hide success message from web page, and same way for hide error alert message here also we have define errorAlert variable with false value. For clear uploaded image division tag data, here also we have set uploadImage variable with blank value.

After define data, we have to define methods, so in this section we have create uploadImage() function which will be called after click on upload button. In this function, first we have add selected file in Vue JS for send selected file to PHP script. Here we have use FormData object for send selected file to PHP script. We will append selected file in FormData() object as data.

After appending data in formData as data, we want to send POST request to upload.php file and pass formData in which we have append selected file has been send with post request as data. We have also set Content-Type: 'multipart/form-data' in header. Once image has been successfully uploaded then it will display success message on web page with uploaded image and suppose there is any error occur during uploading of file then it will display validation error on web page.


<script>

var application = new Vue({
 el:'#uploadApp',
 data:{
  file:'',
  successAlert:false,
  errorAlert:false,
  uploadedImage:'',
 },
 methods:{
  uploadImage:function(){

   application.file = application.$refs.file.files[0];

   var formData = new FormData();

   formData.append('file', application.file);

   axios.post('upload.php', formData, {
    header:{
     'Content-Type' : 'multipart/form-data'
    }
   }).then(function(response){
    if(response.data.image == '')
    {
     application.errorAlert = true;
     application.successAlert = false;
     application.errorMessage = response.data.message;
     application.successMessage = '';
     application.uploadedImage = '';
    }
    else
    {
     application.errorAlert = false;
     application.successAlert = true;
     application.errorMessage = '';
     application.successMessage = response.data.message;
     var image_html = "<img src='"+response.data.image+"' class='img-thumbnail' width='200' />";
     application.uploadedImage = image_html;
     application.$refs.file.value = '';
    }
   });
  }
 },
});
</script>


upload.php


So here our HTML and Vue JS code is ready now we have move to write PHP code in upload.php file. This file will first check user has select file or not, if user has not select file then it will display validation error.

If User has select file, then it will proceed for another validation and it will check selected file has valid extension. If selected file has not valid extension then it will display validation error on web page.

If Selected file has valid extension, then it will first create new name for selected file before uploading of image. After this it will upload selected image file in upload directive and send success message with uploaded image path as data to Axios request in json format. Below you can find complete PHP script for upload image in upload directive.


<?php

//upload.php

$image = '';

if(isset($_FILES['file']['name']))
{
 $image_name = $_FILES['file']['name'];
 $valid_extensions = array("jpg","jpeg","png");
 $extension = pathinfo($image_name, PATHINFO_EXTENSION);
 if(in_array($extension, $valid_extensions))
 {
  $upload_path = 'upload/' . time() . '.' . $extension;
  if(move_uploaded_file($_FILES['file']['tmp_name'], $upload_path))
  {
   $message = 'Image Uploaded';
   $image = $upload_path;
  }
  else
  {
   $message = 'There is an error while uploading image';
  }
 }
 else
 {
  $message = 'Only .jpg, .jpeg and .png Image allowed to upload';
 }
}
else
{
 $message = 'Select Image';
}

$output = array(
 'message'  => $message,
 'image'   => $image
);

echo json_encode($output);


?>


So, this is complete step by step guide for upload file using Vue.js with PHP script and Axios package. I hope you have understand this file uploading process using VueJS with PHP script.

1 comment: