AngularJS: file upload via angular JS

My current scenario: I repeat the repetition of nesting as follows:

$scope.uploadPic = function(file) 
{

    alert($scope.taskdetails.id);       //task_id e.g 21
    alert($rootScope.job_id);   //job_id e.g 12
    file.upload = Upload.upload(
    {
      url: 'http://localhost/mobile-data/upload_file.php',
      data: {
                file: file,
                task_id: $scope.taskdetails.id,
                job_id: $rootScope.job_id
            },

    });
    file.upload.then(function (response) {
      $timeout(function () {
        file.result = response.data;
      });
    }, function (response) {
      if (response.status > 0)
        $scope.errorMsg = response.status + ': ' + response.data;
    }, function (evt) {
      // Math.min is to fix IE which reports 200% sometimes
      file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
    });
}   

but on mine upload_file.phpI cannot get values ​​for:

task_id: $scope.taskdetails.id,
job_id: $rootScope.job_id

in console.logthey are working properly. but on the server side it does not receive. here is my codeupload_file.php

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('content-type: application/json; charset=utf-8');
$_POST = json_decode(file_get_contents('php://input'), true);

$task_id = $_POST["task_id"];
$file = $_FILES["file"];
$job_id = $_POST["job_id"];
var_dump($task_id);
var_dump($job_id);

but on var_dumpit prints only zero. Help me get the values ​​right.

+4
source share
1 answer

In your php file, delete the decoding line that:

$_POST = json_decode(file_get_contents('php://input'), true);

You do not need to decrypt, because you are not receiving data in a encoded JSON array ...

+2
source

Source: https://habr.com/ru/post/1623275/


All Articles