0

I have created a file upload using angular and php. I am using FormData to send the file to backend. File is appending in the UI side but not able to access using $_FILES['file']['name'].

error_log: Undefined index: file in /home/yrpj2p9qt7gb/public_html/upload.php on line 3

Below is my code.

index.html with ng-file='uploadfiles' as a custom directive

<form method="POST" enctype="multipart/form-data">
            <label class="dash-form_label">Image</label>
            <input type='file' name='file' id='file' ng-file='uploadfiles'>
            <br>
            <input type='button' value='Upload' id='upload' ng-click='upload()'>

        </form>

app.js

app.controller('dashboardCtrl', DashboardCtrl);
app.directive('ngFile', ['$parse', function ($parse) {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            console.log(scope, element, attrs);
            element.bind('change', function () {
                $parse(attrs.ngFile).assign(scope, element[0].files)
                scope.$apply();
            })
        }
    }
}]);

function DashboardCtrl($scope, $http) {
    $scope.upload = function () {
        console.log($scope.uploadfiles);
        var fd = new FormData();
        angular.forEach($scope.uploadfiles, function (File) {
            fd.append('file', File);
        });
        console.log(fd.get('file'));

        $http({
            method: 'post',
            url: '../../upload.php',
            data: fd,
            header: { 'Content-Type': undefined }
        }).then(function successCallback(response) {
            $scope.response = response.data;
            console.log($scope.response);
        }, function (err) {
            console.log(err);
        })
    };
};

upload.php

<?php
/* Getting file name */
$filename = $_FILES['file']['name'];

/* Location */
$location = 'upload/';

/* Upload file */
move_uploaded_file($_FILES['file']['tmp_name'],$location.$filename);

$arr = array("name"=>$filename);
echo json_encode($arr);
Jijo Cleetus
  • 2,679
  • 1
  • 11
  • 17
  • 1
    There are many reasons this can go wrong, but maybe you should `var_dump($_FILES)` or `print_r($_FILES)` too first of all; see if your file is in there and second of all; make sure you grab the right indexes. -- Another thing where it can go wrong is that formdata can't be contenttyped or handled or it'll break. Had a similar issue with jQuery. Have you seen this post:? https://stackoverflow.com/questions/37039852/send-formdata-with-other-field-in-angular – NoobishPro Mar 31 '18 at 15:53
  • i had did a `var_dump($_FILES)` and seems like it is not getting the files.below is the output `array(0) { }` – Jijo Cleetus Mar 31 '18 at 16:13

0 Answers0