IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

PHP & Base de données Discussion :

Upload fil via un front avec angular


Sujet :

PHP & Base de données

  1. #1
    Membre confirmé
    Femme Profil pro
    Développeur Web
    Inscrit en
    Mars 2021
    Messages
    82
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : France, Bouches du Rhône (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Développeur Web

    Informations forums :
    Inscription : Mars 2021
    Messages : 82
    Par défaut Upload fil via un front avec angular
    Bonjour,

    J'ai un problème avec mes fichier pour télécharger sur le serveur des fichiers. Sur mon projet, je travail donc PHP natif pour le back et sous framework Angular pour le front. Mais je n'arrive pas à savoir si mon problème vient du back ou du front car rien ne se télécharge. Donc la bdd j'ai la création d'une nouvelle avec toutes les autres infos que j'ai récupérer du formulaire mais je. n'ai pas mon fichier de télécharger sur le serveur.

    Voici mon code PHP

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    <?php
    class TechnicalControlInvoice 
    {
        private $conn;
        private $table = "technicalControlInvoices";
     
        public $idTechnicalControlInvoices;
        public $idPartner;
        public $monthlyInvoice;
        public $urlInvoice;
        public $priceInvoice;
     
        public function __construct($db) 
        {
            $this->conn = $db;
        }
     
        public function createInvoice() 
        {
            $query = "
                INSERT INTO "
                . $this->table .
                " SET
                idPartner = :idPartner,
                monthlyInvoice = :monthlyInvoice,
                urlInvoice = :urlInvoice,
                priceInvoice = :priceInvoice
            ";
            $stmt = $this->conn->prepare($query);
     
            $params = [
                "idPartner" => htmlspecialchars(strip_tags($this->idPartner)),
                "monthlyInvoice" => htmlspecialchars(strip_tags($this->monthlyInvoice)),
                "urlInvoice" => htmlspecialchars(strip_tags($this->urlInvoice)),
                "priceInvoice" => htmlspecialchars(strip_tags($this->priceInvoice))
            ];
     
            if($stmt->execute($params)) {
                return true;
            }
            return false;
        }
     
        public function listInvoices() 
        {
            $query = "
            SELECT *
            FROM "
            . $this->table;
            $stmt = $this->conn->prepare($query);
     
            $stmt->execute();
     
            return $stmt;
        }
     
        public function searchInvoicesByPartner() 
        {
            $query = "
                SELECT *
                FROM " . $this->table . "
                WHERE idPartner = :idPartner";
            $stmt = $this->conn->prepare($query);
     
            $params = ["idPartner" => htmlspecialchars(strip_tags($this->idPartner))];
     
            if($stmt->execute($params)) {
                return $stmt;
            }
            return false;
        }
     
        public function searchInvoiceById() 
        {
            $query = "
                SELECT *
                FROM " . $this->table . "
                WHERE idTechnicalControlInvoices = :idTechnicalControlInvoices";
            $stmt = $this->conn->prepare($query);
     
            $params = ["idTechnicalControlInvoices" => htmlspecialchars(strip_tags($this->idTechnicalControlInvoices))];
     
            if($stmt->execute($params)) {
                $row = $stmt->fetch();
                return $row;
            }
            return false;
        }
    }
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    <?php
    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Methods: POST");
    header("Content-Type: application/json");
    header("Access-Control-Allow-Headers: Access-Control-Allow-Headers, Access-Control-Allow-Methods, Content-Type, Authorization, X-Requested-With");
    include_once "../../config/Database.php";
    include_once "../../models/TechnicalControlInvoice.php";
     
    $db = new Database();
    $conn = $db->connect();
    $technicalControlInvoice = new TechnicalControlInvoice($conn);
     
    $decodedData = json_decode(file_get_contents("php://input"));
     
    $technicalControlInvoice->idPartner = $decodedData->idPartner;
    $technicalControlInvoice->monthlyInvoice = $decodedData->monthlyInvoice;
    $technicalControlInvoice->priceInvoice = $decodedData->priceInvoice;
     
    $uploadDirectory = 'factureTEchnicalControl/';
    $extensions = [
        'jpg',
        'jpeg',
        'png',
        'gif'
    ];
     
    echo json_encode($_FILES['saveName']);
    echo json_encode($_FILES['saveName']['error']);
     
     
    if (isset($_FILES) && !empty($_FILES['image'])) {
        echo json_encode('isset$_FILES ok');
        $extension = strtolower(pathinfo($_FILES['image']['name'],PATHINFO_EXTENSION));
        if (in_array($extension, $extensions)) {
    		$saveName = htmlspecialchars(strip_tags($decodedData->idPartner)).'-'.htmlspecialchars(strip_tags($decodedData->monthlyInvoice)).'-'.uniqid().$extension;
    		move_uploaded_file($_FILES['image']['tmp_name'], '../../' . $uploadDirectory . $saveName);
    		$technicalControlInvoice->urlInvoice = $saveName;
        } else {
            echo json_encode('Le format de l\'image '. $_FILES['image']['name'] .' n\'est pas bon');
        }
    }
     
        $result = $technicalControlInvoice->createInvoice($technicalControlInvoice);
     
    if ($result) {
        echo json_encode([ "message" => "La facture a été édité !" ]);
    }  else { 
        echo json_encode([ "message" => "La facture n'a pas pu être édité..." ]);
    }
    Je met également mon code en angular
    Code html : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    <div class="row mt-5 mb-5">
      <div class="col-12 text-center">
          <h2>Ajout d'une facture</h2>
      </div>
    </div>
     
    <div class="row">
      <div *ngIf="uploadResponse && uploadResponse.status === 'error'">
     
      </div>
      <div *ngIf="uploadResponse && uploadResponse.status === 'success'">
        <img [src]='uploadResponse.url' />
      </div>
     
      <form class="col-10 offset-1" enctype="multipart/form-data" [formGroup]="billingForm" (ngSubmit)="onSubmit()">
        <div class="row d-flex flex-column">
          <div class="input-field d-flex flex-row mb">
              <div class="input-field col-4">
                <label for="monthlyInvoice">Mois de la facture</label>
                <input required type="text" class="validate" id="monthlyInvoice" formControlName="monthlyInvoice">
                <!-- <div class="messageError">
                    <sup>*</sup>Champ obligatoire
                </div> -->
              </div>
              <div class="input-field col-4">
                <label for="priceInvoice">Montant de la facture</label>
                <input required type="text" class="validate" id="priceInvoice" formControlName="priceInvoice">
                <!-- <div class="messageError">
                    <sup>*</sup>Champ obligatoire
                </div> -->
              </div>
              <div class="input-field col-4">
                <label for="saveName">Adresse de l'agence</label>
                <input type="file" name="saveName" (change)="onFileSelect($event)" />
                <!-- <div class="messageError">
                    <sup>*</sup>Champ obligatoire
                </div> -->
              </div>
          </div>
        </div>
        <div class="mt-5 mb-5 text-center">
          <button class="m-auto" id="btn" type="submit" [disabled]="billingForm.invalid">Ajouter une facture</button>
        </div>
      </form>
    </div>

    Code TypeScript : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    import { FormBuilder, FormGroup, Validators } from '@angular/forms';
    import { Component, OnInit } from '@angular/core';
    import { BillingService } from 'src/app/services/billing.service';
    import { Billing } from 'src/app/models/billing.model';
    import { Subscription } from 'rxjs';
    import { Router } from '@angular/router';
     
    @Component({
      selector: 'app-billing-forms',
      templateUrl: './billing-forms.component.html',
      styleUrls: ['./billing-forms.component.css']
    })
    export class BillingFormsComponent implements OnInit {
     
      billingForm: FormGroup;
      uploadResponse;
      billings: Billing[];
      billingSubscription: Subscription;
      idPartner = JSON.parse(localStorage.getItem('idPartner'));
     
     
      constructor(private formBuilder: FormBuilder, private billingService: BillingService, private router: Router) { }
     
      ngOnInit(): void {
        this.billingSubscription = this.billingService.billingSubject.subscribe(
          (billings: Billing[]) => {
            this.billings = billings;
          }
        );
        this.billingService.emitBillingSubject();
        this.initFormBilling();
      }
     
      initFormBilling() {
        this.billingForm = this.formBuilder.group({
          idTechnicalControlInvoices: '',
          monthlyInvoice: ['', Validators.required],
          priceInvoice: ['', Validators.required],
          saveName: ['']
        });
      }
     
      onFileSelect(event) {
        if (event.target.files.length > 0) {
          const file = event.target.files[0];
          this.billingForm.patchValue({
            urlInvoiceSource: file
          });
          console.log(this.billingForm.patchValue({
            urlInvoice: file
          }))
        }
      }
     
      onSubmit() {
        console.log(1111);
        const newBilling = new Billing();
        newBilling.idPartner = this.idPartner;
        newBilling.monthlyInvoice = this.billingForm.value.monthlyInvoice;
        newBilling.priceInvoice = this.billingForm.value.priceInvoice;
        newBilling.saveName = this.billingForm.value.urlInvoiceSource;
        this.billingService.addBilling(newBilling);
        this.router.navigate(['/facture']);
        return this.billingService.addBilling(newBilling);
      }
    }

    Code TypeScript : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    import { Injectable } from '@angular/core';
    import { Subject } from 'rxjs';
    import { HttpClient } from '@angular/common/http';
    import { Billing } from 'src/app/models/billing.model';
     
    @Injectable({
      providedIn: 'root'
    })
    export class BillingService {
     
      billingSubject = new Subject<Billing[]>();
      baseUrl =  'http://localhost:8888/MoutteCAPI/backend/api/technicalControlInvoices';
      private billings: Billing[];
     
      constructor(private httpClient: HttpClient) { }
     
      emitBillingSubject() {
        this.billingSubject.next(this.billings);
      }
     
      readListBilling() {
        this.httpClient.get<Billing[]> (`${this.baseUrl}/listInvoices.php`).subscribe(
          (response) => {
            this.billings = response;
            this.emitBillingSubject();
          },
          (error) => {
            console.log('erreur de sauvegarde' + error);
          }
        );
        return this.httpClient.get<[]>(`${this.baseUrl}/listInvoices.php`);
      }
     
      addBilling(billing: Billing) {
        this.httpClient.post(`http://localhost:8888/MoutteCAPI/backend/api/car/editCar.php`, billing).subscribe(
          () => {
            this.billings.push(billing)
          },
          (error) => {
            console.log('erreur de sauvegarde de la facture', + error);
          }
        );
        // return this.httpClient.post(`http://localhost:8888/MoutteCAPI/backend/api/car/editCar.php`, billing);
      }
    }

    J'aimerais donc bien trouver d'où vient mon erreur.

  2. #2
    Membre éprouvé
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Avril 2020
    Messages
    35
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Ain (Rhône Alpes)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels

    Informations forums :
    Inscription : Avril 2020
    Messages : 35
    Par défaut
    Salut,
    As-tu pu trouver une solution?

    Sinon, côté PHP j'ai remarqué certaines incohérences.
    Premièrement, ta méthode createInvoice est appelée (ligne 43) avec un argument, ce qui ne correspond pas à la signature présente dans ta classe TechnicalControlInvoice.
    Deuxièmement, tu fais plusieurs appels à json_encode (pour le debug?), ce qui pourrait au final générer un json invalide.
    Et as-tu vérifié que move_uploaded_file renvoyait bien true?

Discussions similaires

  1. Uploader une fichiers excel avec angular
    Par 78994273 dans le forum Angular
    Réponses: 1
    Dernier message: 22/10/2020, 23h07
  2. Réponses: 4
    Dernier message: 12/02/2018, 14h21
  3. Réponses: 1
    Dernier message: 31/10/2005, 09h33
  4. [Web] Upload fichier via formulaire HTTP
    Par nik00s dans le forum Entrée/Sortie
    Réponses: 2
    Dernier message: 11/08/2005, 12h27
  5. Generer du xml via SQL(oracle) avec de l'asp
    Par jpg dans le forum XQUERY/SGBD
    Réponses: 6
    Dernier message: 03/08/2004, 12h36

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo