File uploads with Vue and PHP

File uploads with Vue and PHP

Vue CLI and PHP

Make PHP great again was my motto but realised it's actually great. It has been a while since I last wrote an article here. Started and went back to school. Back to making PHP great again.

Today We are going to focus on file uploads and VueJs V3.

Prerequisites

  • Knowledge of Javascript and of course Vue Js
  • PHP basics
  • Will to learn something new

Let's get started

Vue Js is a JS framework. Of course you know that. Yeah, I know there are numerous JS frameworks but well this one is really great. Powerful CLI and big community to help with any questions you may have.

Assuming you didn't jump to Js directly but know HTML. I'll use the Vue CLI method cause I didn't seem to find any article that spoke about it. If you don't know about the vue CLI oor how to install it read the docs here Let's jump into it. In your template add this input code below

<input type="file" ref="file"   name="file[]" id="file" @change="fileUpload">

A few things here:

@ change well listens for the event change of input such that when the user selects a file then it needs to do something. In our case we want the file sent to a PHP file for processing.

fileUpload is the method we want invoked when change occurs. We will write the method on the script section of the vue file.

Well we don't need a submit button. We will need it later for the bonus section but for now that will do.

Now we will use the options api and not the composition api. Add the following code on the options.

data:{
file : " ",
},
methods: {
 fileUpload() {
            var formData = new FormData();
                this.file = this.$refs.file.files[1];
                formData.append('file', this.file);
},

FormData Interface is a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest.send() method.(source Read more on MDN )

Well time to send it to a file.php file which we will create later. We will use axios. Install Vue-axios.

npm install --save axios vue-axios

Import it on your template

import axios from 'axios'

Add the following cod to the file fileUpload() method

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

Well we are almost there. We have sent the file to a php file that will handle the processing. First create a folder Uploads

mkdir Uploads

Get your server started time for PHP. The file will receive the file and handle using the following code. Create a file.php and add the following code.

<?php

  header("Content-Type:Application/Json;charset=UTF-8");
  header("Access-Control-Allow-Origin: *");
  header("Content-Type': 'multipart/form-data");

$valid = array("jpg","jpeg","png","pdf");

$filename = $_FILES["file"]["name"];

$ext = pathinfo($filename, PATHINFO_EXTENSION);


if (isset($_FILES['file']['name'])) {
    if (in_array($ext, $valid)) {
        move_uploaded_file($_FILES['file']['tmp_name'], './upload/'.$filename);

    }
}

header("Access-Control-Allow-Origin: *") means no authentication required.
move_uploaded_file() is an in-built PHP method for file handling.

Read more about files here. There is whole universe on files there.

We first create an array of valid files we are expecting and check them against the file uploaded. If valid then we move the uploaded file to the Uploads folder.

Just like that we have uploaded the file.