How To Upload Multiple Files using AngularJS with PHP/MySQLi

1 12,536

In this article we are Teach you how to upload multiple Files using AngularJS with PHP/MySQLi. We will simplify the upload multiple images. using this script you can upload multiple images at once with help of AngularJS and PHP/MySQLi. We will show you two ways to display images after upload . Once the images are uploaded to the Server . and Second one is you can Display images stored in a Folder. This Script is easy and usefull which you can implemented in your web pages easily. I’ve used CDN for Bootstrap and Angular JS so you need internet connection for them to work.

How To Upload Multiple Files using AngularJS with PHP/MySQLi

1-Creating Database

  • Open Phpmyadmin in your Browser
  • Click on Database Tab Display on Top side
  • Give the Database name “angular”.
  • After Creating Database Open it.
  • Click on SQL Tab on Top area
  • Copy the Below Source Code and paste it.
  • Then Click on Go.
-- phpMyAdmin SQL Dump
-- version 4.7.0
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Jan 02, 2018 at 11:07 AM
-- Server version: 10.1.25-MariaDB
-- PHP Version: 5.6.31

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `angular`
--

-- --------------------------------------------------------

--
-- Table structure for table `upload`
--

CREATE TABLE `upload` (
  `imageid` int(11) NOT NULL,
  `filename` varchar(200) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `upload`
--

INSERT INTO `upload` (`imageid`, `filename`) VALUES
(58, '1514885049_1.jpg'),
(59, '1514885049_2.jpg'),
(60, '1514885049_3.jpg'),
(61, '1514885049_4.jpg'),
(62, '1514885049_5.jpg');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `upload`
--
ALTER TABLE `upload`
  ADD PRIMARY KEY (`imageid`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `upload`
--
ALTER TABLE `upload`
  MODIFY `imageid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=63;COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

OR Import DB File

After Downloading the source code extract it in your root folder.

  • Open Phpmyadmin in your Browser
  • Click on Database Tab Display on Top side
  • Give the Database name “angular”.
  • After Creating Database Open it.
  • Click on Import Tab on Top area
  • You can Find Database folder in  Downloaded source code where find register.sql file then Select it.
  • Then Click on Go.

2- Creating Index File Where Show Uploading Form

in this step we are going to create uploading form for upload file and show uploaded files in the index page.

<!DOCTYPE html>
<html >
	<head>
		<title>How TO Upload Multiple Files using AngularJS with PHP/MySQLi</title>
		<meta charset="utf-8">
			<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
				<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
				<style>
				#sidebar {

  height:100%;
  position:fixed;
  right:90px;
}
			</style>
			</head>
			<body ng-app="app" ng-controller="uploader" ng-init="fetch()">
				<div class="container">
					<h1 class="jumbotron">How TO Upload Multiple Files using AngularJS with PHP/MySQLi</h1>
					<div class="row">
						<div class="col-md-3" id="sidebar">
							<div class="panel panel-success">
								<div class="panel-heading">
									<h4>Upload Files</h4>
								</div>
								<div class="panel-body">
									<label>File:</label>
									<input type="file" file-input="files" multiple>
										<hr>
											<button class="btn btn-success" ng-click="upload()">
												<span class="glyphicon glyphicon-download-alt"></span> Upload
											</button>
										</div>
										<div class="panel-footer">
											<div ng-show="error" class="alert alert-danger text-center" style="margin-top:30px;">
												<button type="button" class="close" ng-click="clearMessage()">
													<span aria-hidden="true">&times;</span>
												</button>
												<span class="glyphicon glyphicon-remove"></span> {{ errorMessage }}
						
											</div>
											<div ng-show="success" class="alert alert-success text-center" style="margin-top:30px;">
												<button type="button" class="close" ng-click="clearMessage()">
													<span aria-hidden="true">&times;</span>
												</button>
												<span class="glyphicon glyphicon-check"></span> {{ successMessage }}
						
											</div>
										</div>
									</div>
								</div>
								<div class="col-md-9">
									<div class="col-md-4" ng-repeat="image in images">
										<img ng-src="upload/{{ image.filename }}" width="100%" height="250px" class="thumbnail">
										</div>
									</div>
								</div>
							</div>
							<script src="angular.js"></script>
						</body>
					</html>

3- Creating Angular JS Script

in this step we are creating angular js script to uploading multiple file into database and fetch data from database.

var app = angular.module('app', []);
app.directive('fileInput', ['$parse', function ($parse) {
	return {
		restrict: 'A',
		link: function($scope, elm, attrs){
			elm.bind('change', function(){
				$parse(attrs.fileInput).assign($scope, elm[0].files);
				$scope.$apply();
			});
		}
	}
}]);
app.controller('uploader', function($scope, $http){

	$scope.error = false;
	$scope.errorMessage = "";
	$scope.success = false;
	$scope.successMessage = "";
	$scope.upload = function(){
	    var uploadForm = new FormData();

	    angular.forEach($scope.files, function (file) {
            uploadForm.append('file', file);
        });

	    var value = uploadForm.getAll('file');
	   	console.log(value);

		var uploadForm = new FormData();
		angular.forEach($scope.files, function(file){
			uploadForm.append('file[]', file);
		});
		$http.post('upload.php', uploadForm, {
			transformRequest:angular.identity, 
			headers: {'Content-Type':undefined, 'Process-Data': false}
		}).success(function(response){
			console.log(response);
			if(response.error){
				$scope.error = true;
				$scope.errorMessage = response.message;
			}
			else{
				$scope.success = true;
				$scope.successMessage = response.message;
				$scope.fetch();
			}
		})
	}

	$scope.fetch = function(){
		$http.get('fetch.php')
		.success(function(data){
			$scope.images = data;
		});

	}

	$scope.clearMessage = function(){
		$scope.error = false;
		$scope.errorMessage = "";
		$scope.success = false;
		$scope.successMessage = "";
	}	
});

4- Upload File Into MySQL Database using PHP

in this step we are going to create php script who send upload files into mysql database.

<?php

	$conn = new mysqli('localhost', 'root', '', 'angular');
	$out = array('error' => false);

	if(!empty($_FILES['file']['name'])){
		$count = count($_FILES['file']['name']);
		foreach ($_FILES['file']['name'] as $key => $filename){
			$newFilename = time() . "_" . $filename;

			$path = 'upload/' . $newFilename;

			if(move_uploaded_file($_FILES['file']['tmp_name'][$key], $path)){
				$sql = "INSERT INTO upload (filename) VALUES ('$newFilename')";
				$query=$conn->query($sql);
			}
			 	
			if($query){
				if($count > 1){
					$out['message'] = 'Files Uploaded Successfully';
				}
				else{
					$out['message'] = 'File Uploaded Successfully';
				}
				
			}
			else{
				$out['error'] = true;
				$out['message'] = 'File Uploaded but not Saved';
			}
		
		}
	}
	else{
		$out['error'] = true;
		$out['message'] = 'Upload Failed. File empty!';
	}

	echo json_encode($out);
?>

5- Fetch Data From Database

in this step we are going to fetch data from database using Angular JS with PHP.

<?php
	$conn = new mysqli('localhost', 'root', '', 'angular');
	$output = array();
	$sql = "SELECT * FROM upload";
	$query=$conn->query($sql);
	while($row=$query->fetch_array()){
		$output[] = $row;
	}

	echo json_encode($output);
?>

How To Upload Multiple Files using AngularJS with PHP/MySQLi

If you facing any type of problem with this source code then you can Download the Complete source code in zip Formate by clicking the below button Download Now otherwise you can send Comment.

Download Source Code

1 Comment
  1. Hassam says

    Thanks for this code. I try to do it myself but i faced some erors NOW you code helps to remove bugs or errors in my code. THANKS!

Leave A Reply

Your email address will not be published.