Web technology is improving vastly day by day. Rather than refreshing pages with every action, a dynamic action can improve UX massively. Image upload is one of the most common tasks that the majority of websites perform. So today we will learn how to upload images dynamically with our Codeigniter Vue image upload tutorial.

Codeigniter is one of the most popular lightweight PHP frameworks. It’s beginner-friendly and comes with a lot of great features. If you are not comfortable with Codeigniter then you can check Laravel. We have chosen Codeigniter for this tutorial as it’s really easy to understand.

Vue Js is an amazing JavaScript framework. In a short span of time, it becomes the top choice of JavaScript developers.

Axios is a library that makes it really easy to use HTTP requests. In this article, we will check how it can be used along with Vue js.

Codeigniter Vue image upload

First of all, you’ll need a server like XAMPP/LAMPP or WAMP to get started. If you don’t have it installed then you can download it by clicking on the above links.

Once the PHP server has been installed create a new folder inside of your root project directory. Depending on your servers it will be either htdocs or www. Now go straight and download Codeigniter. We are using the latest version of 3.x for this tutorial.

After the download has been completed. Go straight inside your project directory and extract it. Now open the folder in your favorite text editor.

Creating the upload controller

The controller is the most important part. At first, go inside the application/controllers directory and create a new controller called upload. That upload controller will contain two methods and a constructor. Let’s create the base structure of a CodeIgniter controller first.

<?php
class Upload extends CI_Controller {
    public function __construct() {
        parent::__construct();
        $this->load->helper(array('form', 'url'));
    }
?>

As we will deal with form validations and URLs so we have added those helper classes. Once the contractor is ready let’s move to the index method.

The index method serves as the entry point of our controller. Suppose you put your project inside a folder called test. When you will visit localhost/test/upload URL then it will execute the code inside of the index method.

Generally, for this project, the index method will load a view as follows.

public function index() {
    $this->load->view('upload_form');
}

Now when we will visit the upload URL it will show us the upload form. However, we haven’t yet specified what will happen when we submit that form. So in order to handle that we will create a do_upload method. This method will validate the uploaded image and return data.

public function do_upload() {
    $config['upload_path']          = './uploads/';
    $config['allowed_types']        = 'gif|jpg|png|jpeg';
    $config['max_size']             = 500;
    $config['max_width']            = 2500;
    $config['max_height']           = 1400;

    $this->load->library('upload', $config);

    if ( ! $this->upload->do_upload('file')) {
        $error = array('error' => $this->upload->display_errors());
        echo json_encode($error);
    } else {
        $upload_data = $this->upload->data();
        $file_name = $upload_data['file_name'];
        $success = array('success' => "http://localhost/test/uploads/".$file_name);
        echo json_encode($success);
    }
}

In the above code, we have first created the config array. It will work as a validator. Next, we have loaded the library upload and passed the config array to it.

Finally, we have checked if the file is uploaded then we are returning the error array. If the file is successfully updated then we have returned the success array that contains the uploaded image URL.

So that’s all we need to do in our controller now let’s create the front end part.

Creating the upload view

Its the another most important part of our Codeigniter Vue image upload tutorial. Go inside the views folder and create a file called upload_form.php. We will use bootstrap to make things look beautiful. You can use CDN for this purpose. Now write a simple HTML structure and add the code below the inside the body.

<div id="app">
	<div class="container mt-5">
		<div class="row justify-content-center">
			<div class="col-md-8">
				<div class="card bg-light">
					<img src="http://via.placeholder.com/350x150" alt="Image" class="card-img-top" id="image-display">
					<div class="card-body">
						<form id="upload-form" enctype="multipart/form-data" method="post" accept-charset="utf-8" v-on:submit.prevent="upload">
							<div class="form-group">
								<input type="file" class="form-control-file" id="image" name="image">
								</div>
							<button class="btn btn-primary" type="submit">Upload</button>
						</form>	
						<p id="error" class="text-danger pt-3"></p>
					</div>
				</div>
			</div>
		</div>
	</div>
</div>

We have just created a bootstrap card and added a form to it. Notice that the form is bound to the v-on directive. We have bound the submit an event to it. In addition to that event, we have used prevent along with it to prevent the form from submitting.

Defining the JavaScript part

Codeigniter Vue image upload tutorial needs 3 different js files. They are jQueryVue JS, and Axios. We are using CDN and you can use the same too. Now after referring to these 3 scripts, the fourth one will contain our custom JS code.

If you don’t know the basics of Vue JS we would suggest you check the Vue JS todo list.

var app = new Vue({
  	el: '#app',
  	data: {
  		file_data: '',
  		form_data: {},
  	},
  	methods: {
  		upload() {
			this.file_data = $('#image').prop('files')[0];
	        this.form_data = new FormData();
	        this.form_data.append('file', this.file_data);
	        let url = "http://localhost/test/upload/do_upload";
	        var self = this
	            axios
	               	.post(url, this.form_data).then((res) => {
	                	if (res.data.success) {
	                		$('#image-display').attr('src', res.data.success)
	                	}
	                	if (res.data.error) {
	                		$('#error').html(res.data.error)
	                	}
	                });
	    }
	}
});

In the above code, we have created two data variables and initialize them to empty string and object respectively. After that inside of the methods, we have defined our custom method upload. This method will execute on form submit. Inside of the method we have stored the uploaded file name into a file_data variable.

After that, we have used the FormData object and set it to form_data object. Next, we have used the append method to attach the file_data to form_data. In simple words, we have created a form and added an input called a file to it. Which contains the uploaded image name.

Finally, we have stored the upload URL with a variable called URL. Then we have used axios to submit the form.

If the form is successfully submitted then we will change the placeholder image to the uploaded one. Else we will display the error message.

So that’s how you can make your website dynamic with a little effort as described in our Codeigniter vue image upload with axios tutorial. Hope you all have liked this article. If you think we have missed something let us know below in the comment section.