Saturday, September 30, 2017

AngularJS Upload image sending post through $http function

I recently tried to code an upload script which is not really working as it should. The goal is to send a Picture through POST method, using the $http function built in AngularJS.
So I’m basically using AngularJS to get datas from my own API REST and insert them to the dom, my front server and my back server are separated.

But as i want to upload my files directly on the front server, where you only get the DOM features, i decided to create a small script outside my API called upload.php, a little bit like that:
./index.php (get datas and show templates)
./upload.php (upload data)

But here is the trick. My PHP file is a module outside my main framework, which is the only real php script on my front server. It’s working fine, but When i try to use it in background with some js, everything goes wrong. I can’t send datas, or I’m receiving something php cannot read.

It’s starting to mess with my minds as I learned JS all by myself with no outside help.

So here is the PHP script, there is one thing I’m absolutely 100% sure of: I’m not getting the right data of that php://input and I may need to remove this json_decode as I’m maybe not receiving json but POST… I don’t know, I’m so deep lost. And my angular Function, wich is maybe sending things not the right way too. I’m here to learn some more. But please do not try to reinvent the wheel unless it’s really necessary. I’m certain I can do things maybe slightly better, but i have my ways, and i’m willing to go throught another, only if i see something really necessary. Here it is:

<?php
$received_data          = file_get_contents("php://input");
$dataJsonDecode         = json_decode($received_data);

if(isset($dataJsonDecode->packet) && $dataJsonDecode->packet === true) {
  $checker = true;
  $mess= "The following informations are incorrect: <br />";

  if(isset($dataJsonDecode->id) && $dataJsonDecode->id !== null) {
    if(preg_match("#^[0-9]{1,11}$#", $dataJsonDecode->id)) {
      $post1 = $dataJsonDecode->id;
    } else {
      $checker = false;
      $mess .= "- Wrong ID,<br />";
    }
  } else {
    $checker = false;
    $mess .= "- Empty ID,<br />";
  }

  if(!isset($post1)) {
    $post1 = null;
    $checker = false;
    $mess .= "- False ID,<br />";
  }
  $mess .= "Please check at your ID, then try again.";

  if($checker === true) {
    // Constantes
    define('TARGET', '../solocal/img/showcases/');
    define('MAX_SIZE', 100000);
    define('WIDTH_MAX', 800);
    define('HEIGHT_MAX', 800);

    $tabExt = array('jpg','gif','png','jpeg'); 
    $infosImg = array();

    $extension = '';
    $message = '';
    $nomImage = '';
    if(is_dir(TARGET) ) {
      if(!is_dir(TARGET.$post1."/") ) {
        if(!mkdir(TARGET.$post1."/", 0755) ) {
          $attempt = false;
          $message = 'Error: the directory could not be created';
        }
      }
    }

    if(!empty($dataJsonDecode->fichier)) {
      if(!empty($dataJsonDecode->fichier["name"]) ) {
        $extension  = pathinfo($dataJsonDecode->fichier->name, PATHINFO_EXTENSION);

        if(in_array(strtolower($extension),$tabExt)) {
          $infosImg = getimagesize($dataJsonDecode->fichier->tmp_name);

          if($infosImg[2] >= 1 && $infosImg[2] <= 14) {
            if(isset($dataJsonDecode->fichier->error) && UPLOAD_ERR_OK === $dataJsonDecode->fichier->error) {
              $nomImage = 'cover.'. $extension;

              if(move_uploaded_file($dataJsonDecode->fichier->tmp_name, TARGET.$nomImage)) {
                $attempt = true;
                $message = 'Uploaded with success !';
              } else {
                $attempt = false;
                $message = 'An intern error messed it up we are sorry, but you need to upload your file again...';
              }
            } else {
              $attempt = false;
              $message = 'An intern error messed it up we are sorry, but you need to upload your file again...';
            }
          } else {
            $attempt = false;
            $message = 'This file is not a picture !';
          }
        } else {
          $attempt = false;
          $message = 'The file extension is not allowed !';
        }
      } else {
        $attempt = false;
        $message = 'Please fill up the form !';
      }
    } else {
      $attempt = false;
      $message = 'Please fill up the form !';
    }
  } else {
    $attempt = false;
    $message = $mess;
  }
} else {
  $attempt = false;
  $message = 'No datas sent !';
}

$array = array(
  "attempt" => $attempt,
  "message" => $message
  );

echo json_encode($array);
?>

Here is the function i use to read and send this file:

$scope.uploadCover = function(id) {
    var fichier = document.getElementById('fichier').files[0];
    var lecture = new FileReader();
    lecture.onloadend = function(evenement){
    var donnees = evenement.target.result;
        $scope.module.upload = {};
        type_id = typeof id;
        $scope.module.upload.id = type_id.toString();

        if($scope.module.upload.id !== 'undefined' && id !== false && id !== null) { $scope.setter = true; } else { $scope.setter = false; };

        if($scope.setter !== false) {
            $http({
                method: 'POST',
                url: 'http://localhost/dev/goomreactorinterface/admin/upload.php',
                data: {
                    packet: true,
                    id: id,
                    fichier: donnees
                },
                headers: {'Content-Type': 'application/x-www-form-urlencoded'}
            }).then(function successCallback(responsemod) {
                $scope.module.upload.results                = responsemod.data;
                console.log($scope.module.upload.results);
                if($scope.module.upload.results.API) {
                    $scope.module.upload.error          = false;
                    $scope.module.upload.html_message = $sce.trustAsHtml($scope.module.upload.message);
                } else {
                    $scope.module.upload.error = true;
                };
            }, function errorCallback(responsemod) {
                $scope.module.upload.error          = true;
            });
    };
    }
    lecture.readAsBinaryString(fichier);
    $scope.result = null;
    $scope.loadAPI();
};

So i thank you all in advance for your participation, I really hope you i can have a pretty constructive feed.

Peace

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/09/30/angularjs-upload-image-sending-post-through-http-function/
via @lzomedia #developer #freelance #web #lzomedia.com

No comments:

Post a Comment