I have spent days looking for a fairly simple integration of angularjs file upload method that includes a basic php server side script..
I need a simple form one fie
I was also battling with $files being undefined - I'll take a wild guess that you are writing the html code from php and haven't escaped the $ in $files. That was my problem anyway - should be \$files.
Dan
If you use ng-file-upload You can do most of those pre-validation on the client side like checking the file size or type with ngf-max-size or ngf-pattern directives.
Upload.upload() will send a POST multipart/form-data request to the server so $_FILES['file'] should contain the uploaded file.
HTML
<div ng-controller="MyCtrl">
<input type="text" name="username" ng-model="username"/>
<input type="file" ngf-select="onFileSelect($file)" ngf-pattern="'image/*'" ngf-max-size="2M">
</div>
JS:
//inject angular file upload directives and service.
angular.module('myApp', ['ngFileUpload']);
var MyCtrl = [ '$scope', 'Upload', function($scope, Upload) {
$scope.onFileSelect = function(file) {
if (!file) return;
Upload.upload({
url: '/upload.php',
data: {file: file, username: $scope.username}
}).then(function(resp) {
// file is uploaded successfully
console.log(resp.data);
});
};
}];
upload.php
$fname = $_POST["fname"];
if(isset($_FILES['image'])){
//The error validation could be done on the javascript client side.
$errors= array();
$file_name = $_FILES['image']['name'];
$file_size =$_FILES['image']['size'];
$file_tmp =$_FILES['image']['tmp_name'];
$file_type=$_FILES['image']['type'];
$file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
$extensions = array("jpeg","jpg","png");
if(in_array($file_ext,$extensions )=== false){
$errors[]="image extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152){
$errors[]='File size cannot exceed 2 MB';
}
if(empty($errors)==true){
move_uploaded_file($file_tmp,"images/".$file_name);
echo $fname . " uploaded file: " . "images/" . $file_name;
}else{
print_r($errors);
}
}
?>