How to upload array of files with ajax using Codeigniter

I will show you how to upload multiple files using array in Codeigniter, AJAX and jQuery without page refresh. This multiple files upload tutorial example is very helpful to implement the upload functionality. In this example the files are selected using the browse button and files are uploaded to the directory. Codeigniter controller stores files into the defined location and returns response as success or failure messages from the controller.

HTML Code

<form  id="secd_test" method="post" enctype="multipart/form-data" >
	<table class="table">
		<tr>
			<td>Image:1</td>
			<input type="file"  name="return[0][result_file][]"  class="result_file" >
		</tr>
		<tr>
			<td>Image:2</td>
			<input type="file"  name="return[1][result_file][]" class="result_file" >
		</tr>
		<tr>
			<td>Image:3</td>
			<input type="file"  name="return[2][result_file][]" class="result_file" >
		</tr>
		<tr>
			<td colspan="2"><input id="image_upload" value="submit" type="submit" ></td>
		</tr>
	</table>
</form>

Jquery and Ajax Code

<script type="text/javascript">
	$(document).ready(function (e) {
		$("#secd_test").on('submit',(function(e) {
			e.preventDefault();
			$.ajax({
				url: "<?=base_url()?>home/multipleadd_data",
				type: "POST",
				data:  new FormData(this),
				contentType: false,
				cache: false,
				processData:false,
				success: function(data){
					alert('Success');
					data.location();
				},
		   });
		}));
	});
</script>

Controller function(multipleadd_data) Code

public function multipleadd_data()
{
	$stock_item_val = $this->input->post('return');
	if(is_array($_FILES))
	{
		foreach ($_FILES['return']['name'] as $name => $value)
		{
			$sourcePath = $_FILES['return']['tmp_name'][$name]['result_file'][0];//[$name]['result_file'][0]
			$targetPath = "img/".$_FILES['return']['name'][$name]['result_file'][0];
			move_uploaded_file($sourcePath,$targetPath); 
			$data = array('img_path' => $targetPath);
			$this->db->insert('multiple_image', $data);
		}
	}
	echo "yes";
}

Leave a Reply

Your email address will not be published. Required fields are marked *