Angular - 通过 API 上传文件

问题描述 投票:0回答:1

这段代码通过spring boot将axcel导入到数据库sql服务器,所以,我想将spring boot连接到sql server management studio,以练习增删改查操作,但是当我尝试它时,我收到错误:在此处输入图像描述所以,我添加了依赖项:在此处输入图像描述 我添加了属性:在此处输入图像描述...所以,我想将 spring boot 连接到 sql server management studio,以练习 CRUD 操作,但是当我尝试时出现错误:在此处输入图像描述所以,我添加了依赖项:在此处输入图像描述我添加了属性:在此处输入图像描述...

组件

import { Component } from '@angular/core';
import { FileUploadService } from './file-upload.service';

@Component({
  selector: 'app-file-upload',
  templateUrl: './file-upload.component.html',
  styleUrls: ['./file-upload.component.css']
})
export class FileUploadComponent {
  fileToUpload: File | null = null;

  constructor(private fileUploadService: FileUploadService) {}

  handleFileInput(files: FileList): void {
    this.fileToUpload = files.item(0);
  }

  upload(): void {
    if (this.fileToUpload) {
      this.fileUploadService.uploadFile(this.fileToUpload).subscribe(
        data => {
          console.log('Success', data);
        },
        error => {
          console.error('Error', error);
        }
      );
    }
  }
}

HTML

<div>
  <input type="file" (change)="handleFileInput($event.target.files)" />
  <button (click)="upload()">Upload</button>
</div>

这段代码通过spring boot将axcel导入到数据库sql服务器,所以,我想将spring boot连接到sql server management studio,以练习增删改查操作,但是当我尝试它时,我收到错误:在此处输入图像描述所以,我添加了依赖项:在此处输入图像描述 我添加了属性:在此处输入图像描述...所以,我想将 spring boot 连接到 sql server management studio,以练习 CRUD 操作,但是当我尝试时出现错误:在此处输入图像描述所以,我添加了依赖项:在此处输入图像描述我添加了属性:在此处输入图像描述...

服务

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class FileUploadService {
  private baseURL = 'https://mon-api.com/upload';

  constructor(private http: HttpClient) {}

  uploadFile(file: File): Observable<any> {
    const formData: FormData = new FormData();
    formData.append('file', file, file.name);

    return this.http.post(this.baseURL, formData);
  }
}

模块

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';

import { AppComponent } from './app.component';
import { FileUploadComponent } from './file-upload/file-upload.component';
import { FileUploadService } from './file-upload/file-upload.service';

@NgModule({
  declarations: [
    AppComponent,
    FileUploadComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [FileUploadService],
  bootstrap: [AppComponent]
})
export class AppModule { }

android html api file upload
1个回答
0
投票

Component.html

<div class="content-wrapper" id="choice">
  <div class="content-body">
      
    <app-content-header [contentHeader]="contentHeader"></app-content-header>
    
    
    <section id="multiple-column-form">
      <div class="row match-height">
        <div class="col-12">
          <div class="card">
            <div class="card-body">
              <form class="form">
                <div class="row">
                  <div class="col-md-6 col-12">
                    <div class="form-group">
                      <label for="company-column">Période</label>
                      <ng-select name="periode" [items]="periodes" bindLabel="id" bindValue="id"[loading]="selectBasicLoading" (change)="voir($event)">
                        <ng-template ng-label-tmp let-item="item">
                          <span >{{ item.dateDebut | date: 'MMMM y' }} - {{ item.dateFin | date: 'MMMM y' }}</span>
                        </ng-template>
                        <ng-template ng-option-tmp let-item="item" let-index="index">
                          <span >{{ item.dateDebut | date: 'MMMM y' }} - {{ item.dateFin | date: 'MMMM y' }}</span>
                        </ng-template>
                      </ng-select> 
                    </div>
                  </div>
                  
                  <div class="col-md-3 col-12" *ngIf="chooseFiliale">
                    <div class="form-group">
                      <label for="company-column">Filiale</label>
                      <ng-select name="periode" [items]="factures" bindLabel="id" [loading]="selectBasicLoading" [(ngModel)]="facture" (change)="choisirFiliale()" >
                        <ng-template ng-label-tmp let-item="item">
                          <span >{{ item.filiale.nom }}</span>
                        </ng-template>
                        <ng-template ng-option-tmp let-item="item" let-index="index">
                          <span >{{ item.filiale.nom }}</span>
                        </ng-template>
                      </ng-select> 
                    </div>
                  </div>
                  <div class="col-md-3 col-12" *ngIf="chooseFiliale">
                    <div class="form-group">
                      <label for="company-column">Facture T1 a deduire</label>
                      <input type="text" class="form-control" placeholder="Facture" name="filiale" [(ngModel)]="aDeduire"/>
                    </div>
                  </div>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
    </section>
    
  </div>
</div>

<div class="content-wrapper" *ngIf="show">
  <div class="content-body">
    <section class="invoice-preview-wrapper">
      <div class="row invoice-preview">
        <!-- Invoice -->
        <div class="col-xl-9 col-md-8 col-12 printRef">
          <div class="card invoice-preview-card">
            <div class="card-body invoice-padding pb-0">
              <!-- Header Starts -->
              <div class="d-flex justify-content-between flex-md-row flex-column invoice-spacing mt-0">
                <div class="col-xl-12">
                  <div class="logo-wrapper row text-center w-100">
                    <img src="assets/images/logo/favicon.ico" class="mr-auto ml-auto logo"/>
                    <h3 class="invoice-logo font-color-facture mr-auto ml-auto col-12 mt-1">SOCIETE GENERALE MADAGASIKARA</h3>
                  </div>
                </div>
              </div>
            </div>
            <!-- Address And Contact Starts -->
            <div class="card-body invoice-padding pt-0">
              <div class="row invoice-spacing">
                <div class="col-md-9 p-0">
                  <h6 class="font-color-facture">Date:</h6>
                </div>
                <div class="col-md-3 p-0 mt-xl-0 right">
                  <h6 class="font-color-facture">Client: {{ facture.filiale.nom }}</h6>
                  <p class="card-text font-color-facture mb-25"> {{ facture.filiale.rue }} </p>
                  <p class="card-text font-color-facture mb-25">{{ facture.filiale.adresse }} </p>
                </div>
                <div class="col-md-12 p-0 mt-3 centered">
                  <h6 class="font-color-facture">FACTURE N° {{facture.reference}} </h6>
                  <p class="card-text font-color-facture mb-25">DES PRESTATIONS CES</p>
                  <p class="card-text font-color-facture periode mb-25">PERIODE DE FACTURATION: {{ periode.dateDebut | date: 'MMMM' }} A {{ periode.dateFin | date: 'MMMM y' }}</p>
                </div>
              </div>
            </div>
            <!-- Address And Contact Ends -->

            <!-- Invoice Description Starts -->
            <div class="table-responsive facture">
              <table class="font-color-facture">
                <thead>
                  <tr>
                    <th class="py-1 centered"></th>
                    <th class="py-1 centered">Désignation</th>
                    <th class="py-1 centered">Montant en EURO</th>
                  </tr>
                </thead>
                <tbody>
                  <tr >

                    <td class="py-1 no-border" rowspan="2">
                      <p class="card-text text-nowrap">
                        Coût des structures
                      </p>
                    </td>

                  <!--  <td class="py-1 no-border">
                      <p class="card-text text-nowrap">
                        Logistiques  & IT
                        
                      </p>
                    </td>
                    <td class="py-1 no-border">
                      <span class="font-weight-bold right">{{facture.coutLogistiqueAFacturer | number: '1.0-0'}}</span>
                    </td> -->
                  </tr>
                  <tr>

                    <!-- <td class="py-1 no-border">
                      <p class="card-text text-nowrap">
                        Coût de structure 
                      </p>
                    </td> -->

                    <td class="py-1">
                      <p class="card-text text-nowrap">
                        <!-- <ul>
                          <li>UG COO & CODIR </li>
                          <li>Logistiques  & IT</li>
                        </ul> -->
                      
                    </td>
                    <td class="py-1">
                      <span class="font-weight-bold right">{{(facture.coutManagementAFacturer + facture.coutLogistiqueAFacturer) | number: '1.0-2'}}</span>
                    </td>
                  </tr>
                  <tr>

                    <td class="py-1 no-border">
                      <p class="card-text text-nowrap">
                        Coût de Mutualisations
                      </p>
                    </td>
                    <td class="py-1">
                      <tr>Trade Finance</tr>
                      <tr>Flux Internationaux</tr>
                      <tr>Flux Domestiques</tr>
                      <tr>Chèques & effets</tr>
                      <tr>Dossier Client</tr>
                      <tr>Credit Retails</tr>
                    </td>
                    
                    <td class="py-1">
                      <!-- <span class="font-weight-bold right">{{facture.coutMutualisationAFacturer | number: '1.0-2'}}</span> -->
                      <tr class="d-flex justify-content-end"><span class="font-weight-bold right">{{facture.coutActiviteAFacturer[5].montant | number: '1.0-2'}}</span></tr>
                      <tr class="d-flex justify-content-end"><span class="font-weight-bold right">{{facture.coutActiviteAFacturer[6].montant | number: '1.0-2'}}</span></tr>
                      <tr class="d-flex justify-content-end"><span class="font-weight-bold right">{{facture.coutActiviteAFacturer[7].montant | number: '1.0-2'}}</span></tr>
                      <tr class="d-flex justify-content-end"><span class="font-weight-bold right">{{facture.coutActiviteAFacturer[0].montant | number: '1.0-2'}}</span></tr>
                      <tr class="d-flex justify-content-end"><span class="font-weight-bold right">{{facture.coutActiviteAFacturer[3].montant | number: '1.0-2'}}</span></tr>
                      <tr class="d-flex justify-content-end"><span class="font-weight-bold right">{{facture.coutActiviteAFacturer[4].montant | number: '1.0-2'}}</span></tr>
                    </td>
                  </tr>
                  <tr class="bg-primary text-white">

                    <td class="py-1 no-border">
                      <p class="card-text text-nowrap">
                        MONTANT TOTAL
                      </p>
                    </td>

                    <td class="py-1">
                    </td>
                    <td class="py-1">
                      <span class="font-weight-bold right">{{facture.montantTotal | number: '1.0-2'}}</span>
                    </td>
                  </tr>
                  <tr class="bg-primary text-white">

                    <td class="py-1 no-border">
                      <p class="card-text text-nowrap">
                        RETENUE A LA SOURCE
                      </p>
                    </td>

                    <td>
                    <!-- modify farany -->
                    <span class="font-weight-bold right"></span>
                  </td>
                  <td class="py-1">
                      <!-- <span class="font-weight-bold right">{{facture.coutRASAFacturer| number: '1.0-2'}}</span> -->
                      <span class="font-weight-bold right">{{  facture.montantTotal - facture.coutRASAFacturer | number: '1.0-2'}}</span>
                    </td>
                  </tr>
                  <tr class="bg-primary text-white">

                    <td class="py-1 no-border">
                      <p class="card-text text-nowrap">
                        MONTANT TOTAL T2
                      </p>
                    </td>

                    <td class="py-1">
                      
                    </td>
                    <td class="py-1">
                      <span class="font-weight-bold right">{{facture.coutRASAFacturer| number: '1.0-2'}}</span>
                      <!-- <span class="font-weight-bold right">{{facture.montantTotal - facture.coutRASAFacturer | number: '1.0-2'}}</span> -->
                    </td>
                  </tr>
                  <tr class="bg-primary text-white">

                    <td class="py-1 no-border">
                      <p class="card-text text-nowrap">
                        Facture T1 a deduire
                      </p>
                    </td>

                    <td class="py-1">
                      
                    </td>
                    <td class="py-1">
                      <span class="font-weight-bold right">{{aDeduire| number: '1.0-2'}}</span>
                      <!-- <span class="font-weight-bold right">{{facture.montantTotal - facture.coutRASAFacturer | number: '1.0-2'}}</span> -->
                    </td>
                  </tr>
                  <tr class="bg-primary text-white">

                    <td class="py-1 no-border">
                      <p class="card-text text-nowrap">
                        MONTANT A PAYER A LA BFV SG
                      </p>
                    </td>

                    <td class="py-1">
                      
                    </td>
                    <td class="py-1">
                      <span class="font-weight-bold right">{{ (facture.coutRASAFacturer - aDeduire) | number: '1.0-2'}}</span>
                      <!-- <span class="font-weight-bold right">{{facture.montantTotal - facture.coutRASAFacturer | number: '1.0-2'}}</span> -->
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
            
            <!-- Invoice Note Starts -->
            <div class="card-body invoice-padding pt-0 mt-3">
              <div class="row">
                <div class="col-12">
                  <span>Arrêtée la présente facture à la somme de {{ convertirChiffreEnLettre(facture.montantTotal | number: '1.0-0') }} Euros</span>
                </div>
                <div class="col-12 mt-1">
                  <span>Le cours de change utilisé est le cours de la Banque Centrale de Madagascar fin du trimestre : 4697.45 Ariary</span>
                </div>
                <div class="col-12 mt-2">
                  <span>N.B: Tous les frais bancaires et les charges fiscales sont à la charge du payeur</span>
                </div>
                <div class="col-12 mt-3">
                  <span class="text-blue">Règlement sous 30 jours à réception de la présente facture aux références bancaires suivantes:</span>
                </div>
                
                <div class="col-12 mt-1">
                  <span class="text-blue">RIB : 30003 06990 00501 4242 33 -56</span>
                </div>
                <div class="col-12 mt-3 centered">
                  <span>BFV-SOCIETE GENERALE – SA au capital de 14 000 000 000 MGA</span>
                </div>
                <div class="col-12 mt-1 centered">
                  <span>Siège Social : 14, Làlana Jeneraly Rabehevitra  B.P. 196 –Antaninarenina – 101 ANTANANARIVO – 370 MADAGASCAR</span>
                </div>
                <div class="col-12 mt-1 centered">
                  <span>RC 98 B 00 771 –  n° identification  65121 11 1998 0 10078 </span>
                </div>
              </div>
            </div>
            <!-- Invoice Note Ends -->
          </div>
        </div>
        <!--/ Invoice -->

        <!-- Invoice Actions -->
        <div id="actions" class="col-xl-3 col-md-4 col-12 invoice-actions mt-md-0 mt-2">
          <div class="card">
            <div class="card-body">
              <button
                *ngIf="(user.role == 'AGENT_CES' || user.role == 'ROLE_ADMIN') && (saisie.etat.nom == 'Validé') && (!facture.etat || facture.etat.nom == 'Non Validé'); else statut"
                class="btn btn-primary btn-block mb-75"
                data-toggle="modal"
                data-target="#send-invoice-sidebar"
                (click)="toggleSidebar('invoice-sidebar', 'envoi')"
                rippleEffect
              >
                Envoyer pour validation
              </button>
              <ng-template #statut>
                <a class="btn btn-outline-warning text-warning btn-block mb-75" rippleEffect>
                  {{ (facture.etat) ? facture.etat.nom : 'Saisie pas encore validée'}}
                </a>
              </ng-template>
              <a class="btn btn-outline-secondary btn-block mb-75" href="javascript:window.print();" rippleEffect>
                Télécharger
              </a>
              <!-- <button
                class="btn btn-outline-success text-success btn-block mb-75" *ngIf="(user.role == 'ROLE_ADMIN' || user.role == 'FIN') && (facture.etat && facture.etat.nom == 'Envoyé pour validation')"
                (click)="valider()"
                rippleEffect
              >
                Valider
              </button>
              <button
                class="btn btn-outline-primary text-primary btn-block mb-75" *ngIf="(user.role == 'ROLE_ADMIN' || user.role == 'FIN') && (facture.etat && facture.etat.nom == 'Envoyé pour validation')"
                (click)="nePasValider()"
                rippleEffect
              >
                Ne pas valider
            </button> -->
            </div>
          </div>
        </div>
        <!--/ Invoice Actions -->
      </div>
    </section>
  </div>

  
  <!-- Send Invoice Sidebar -->
  <core-sidebar
    class="modal modal-slide-in sidebar-todo-modal fade"
    name="invoice-sidebar"
    overlayClass="modal-backdrop"
    hideOnEsc="true"
  >
    <app-send-invoice-sidebar-diffusion [facture]="facture" [type]="type"></app-send-invoice-sidebar-diffusion>
  </core-sidebar>
  <!--/  Send Invoice Sidebar -->

</div>

组件.ts

import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { Periode } from 'app/models/periode';
import { Saisie } from 'app/models/saisie';
import { SaisieService } from 'app/shared/services/refacturation/saisieService';
import { UserService } from 'app/shared/services/userService';
import { ToastrService } from 'ngx-toastr';
import { Subject } from 'rxjs';
import { saveAs } from 'file-saver';
import { takeUntil } from 'rxjs/operators';
import { FactureService } from 'app/shared/services/refacturation/factureService';
import { Facture } from 'app/models/facture';
import { NumberToLetter } from 'convertir-nombre-lettre';
import { CoreSidebarService } from '@core/components/core-sidebar/core-sidebar.service';
import { User } from 'app/auth/models';
import { AuthenticationService } from 'app/auth/service';

@Component({
  selector: 'app-preview',
  templateUrl: './preview.component.html',
  styleUrls: ['./preview.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class PreviewComponent implements OnInit {

  public contentHeader: object;
  private _unsubscribeAll: Subject<any>;

  
  public periodes : Periode[];
  public periode : Periode;
  public selectBasicLoading = false;
  public idSaisie: number;
  public saisie: Saisie;
  public factures: Facture[];
  public show: boolean = false;
  public chooseFiliale: boolean = false;
  public facture: Facture;
  public user: User;
  public type;
  public aDeduire: number;

  constructor(private toastr: ToastrService, 
    private modalService: NgbModal, 
    private _coreSidebarService: CoreSidebarService,
    private _factureService: FactureService,
    private _authenticationService: AuthenticationService,
    private _service: SaisieService) {
   this._unsubscribeAll = new Subject();
   this.user = this._authenticationService.currentUserValue;
 }

  ngOnInit(): void {
    this.contentHeader = {
      headerTitle: 'Facture',
      actionButton: true,
      breadcrumb: {
        type: '',
        links: [
          {
            name: 'Edition des factures',
            isLink: false
          }
        ]
      }
    };

    this.getPeriodes();

  }

  toastrSuccess(titre, message) {
    this.toastr.success(message, titre, {
      easeTime: 1000,
      toastClass: 'toast ngx-toastr',
      closeButton: true
    });
  }

  toastrError(titre, message) {
    this.toastr.error(message, titre, {
      easeTime: 1000,
      toastClass: 'toast ngx-toastr',
      closeButton: true
    });
  }
  
  getPeriodes(){
    this._service.getPeriodes().pipe(takeUntil(this._unsubscribeAll)).subscribe(response => {
      this.periodes = response.data;
    });
  }

  getFactures(id){
    this._factureService.getFacturesBySaisie(id).pipe(takeUntil(this._unsubscribeAll)).subscribe(response => {
      if(response.code <= 300){
        this.factures = response.data;
        this.factures.forEach(element => {
          console.log(typeof element);
          console.log(element);
        });
        this.chooseFiliale = true;
      }
      else{ 
        this.toastrError("Voir facture", response.message);
      }
    });
  }

  getSaisie(id){
    this._service.getSaisieById(id).pipe(takeUntil(this._unsubscribeAll)).subscribe(response => {
      if(response.code <= 300){
        this.saisie = response.data;
      }
    });

  }

  voir(event){
    this.show = false;
    this.chooseFiliale = false;
    this.facture = null;
    if(event){
      this.periode = event;
      this.getSaisie(this.periode.id)
      this.getFactures(this.periode.id);
    }
  }

  
  downloadFile(id){

    this._service.getPJ(id).pipe(takeUntil(this._unsubscribeAll)).subscribe(response => {
      saveAs(this.dataURItoBlob(response.data.pj), response.data.nomFichier)
    });
  }

  dataURItoBlob(dataURI) {
    const byteString = window.atob(dataURI);
    const arrayBuffer = new ArrayBuffer(byteString.length);
    const int8Array = new Uint8Array(arrayBuffer);
    for (let i = 0; i < byteString.length; i++) {
      int8Array[i] = byteString.charCodeAt(i);
    }
    const blob = new Blob([int8Array]);    
    return blob;
 }

 choisirFiliale(){
  this.show = true;
 }

 convertirChiffreEnLettre(chiffre){
  var nbr = Number(chiffre.replace(/\s/g,''))
  return NumberToLetter(nbr);
 }

 
  /**
   * Toggle the sidebar
   *
   * @param name
   */
  toggleSidebar(name, type): void {
    this.type = type;
    this._coreSidebarService.getSidebarRegistry(name).toggleOpen();
  }

  valider(){
    
    this._factureService.valider(this.facture.id).pipe(takeUntil(this._unsubscribeAll)).subscribe(response => {
      if(response.code <= 300){
        this.toastrSuccess("Validation facture", "Facture validée ! ");
        this.facture = response.data;
      }
      else{
        this.toastrError("Validation facture", response.message);
      }
    });
  }

  nePasValider(){
    
    this._factureService.refuser(this.facture.id).pipe(takeUntil(this._unsubscribeAll)).subscribe(response => {
      if(response.code <= 300){
        this.toastrSuccess("Validation facture", "Facture pas validée ! ");
        this.facture = response.data;
        console.log("facture : " + this.facture)
      }
      else{
        this.toastrError("Validation facture", response.message);
      }
    });
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.