Как добавить несколько изображений из API в angular 8 - PullRequest
0 голосов
/ 08 мая 2020

Я пытаюсь загрузить несколько изображений в angular с помощью API, но всякий раз, когда я пытаюсь загрузить изображения с моими загружаемыми изображениями, это не вызывается или если оно вызывается, одно изображение отправляется несколько раз.

Вот мой HTML файл-

<form [formGroup]="imageFormGroup" >
      <ng-template matStepLabel> Product Images</ng-template>
      <mat-card style="text-align: center;" [class.mat-elevation-z2]="!isActive"
        [class.mat-elevation-z8]="isActive">
        <mat-card-title>Add Product Images</mat-card-title>
      <div fxLayout="row">
          <div>
            <input #file type="file"   accept='image/*' (change)="onFileChanged1($event); preview(file.files)" style="margin-bottom:20px;"
                              formControlName="productImg1"  />
                          <!-- <img *ngIf="this.photo_doclabel" src={{this.photo_doclabel}} height="200" width="200"> -->
          </div>
          <div>
            <input #file type="file"   accept='image/*' (change)="onFileChanged2($event); preview(file.files)" style="margin-bottom:20px;"
                              formControlName="productImg2"  />
                          <!-- <img *ngIf="this.photo_doclabel" src={{this.photo_doclabel}} height="200" width="200"> -->
          </div>
          <div>
            <input #file type="file"  accept='image/*' (change)="onFileChanged3($event); preview(file.files)" style="margin-bottom:20px;"
                              formControlName="productImg3"  />
                          <!-- <img *ngIf="this.photo_doclabel" src={{this.photo_doclabel}} height="200" width="200"> -->
          </div>
      </div>
      <div fxLayout="row">
          <div>
            <input #file type="file"   accept='image/*' (change)="onFileChanged4($event); preview(file.files)" style="margin-bottom:20px;"
                              formControlName="productImg4"  />
                          <!-- <img *ngIf="this.photo_doclabel" src={{this.photo_doclabel}} height="200" width="200"> -->
          </div>
          <div>
            <input #file type="file"   accept='image/*' (change)="onFileChanged5($event); preview(file.files)" style="margin-bottom:20px;"
                              formControlName="productImg5"  />
                          <!-- <img *ngIf="this.photo_doclabel" src={{this.photo_doclabel}} height="200" width="200"> -->
          </div>
          <div>
            <input #file type="file"  accept='image/*' (change)="onFileChanged6($event); preview(file.files)" style="margin-bottom:20px;"
                              formControlName="productImg6"  />
                          <!-- <img *ngIf="this.photo_doclabel" src={{this.photo_doclabel}} height="200" width="200"> -->
          </div>
      </div>

      <div class="text-center mt-3" fxLayout="row" fxLayoutAlign="space-around center">
          <button mat-button matStepperPrevious style=" background-color: #d5ae4f; color: #112b3a;">Back</button>
          <button  mat-button style=" background-color: #d5ae4f; color: #112b3a;"  (click)="addAllImages()"> Add Images</button>
        <span *ngIf="showLoader==true">
          <mat-spinner></mat-spinner>
        </span>
        <span *ngIf="showLoader==false">
          <button mat-button matStepperNext  style=" background-color: #d5ae4f; color: #112b3a;">Next</button>
        </span>

      </div>

      </mat-card>
  </form>

Мой файл component.ts-

    import { Component, OnInit ,ChangeDetectorRef, ElementRef, ViewChild, Inject } from '@angular/core';
import { FormBuilder, FormGroup, FormArray, FormControl,Validators } from '@angular/forms';
import { DefaultAdminService } from '../default-admin.service';
import {MatSnackBar} from '@angular/material/snack-bar';
//import {SESSION_STORAGE, WebStorageService} from 'angular-webstorage-service';

import { of } from 'rxjs';  
import { catchError, map } from 'rxjs/operators'; 

// class ImageSnippet {
//   constructor(public src: string, public file: File) {}
// }


@Component({
  selector: 'app-add-product',
  templateUrl: './add-product.component.html',
  styleUrls: ['./add-product.component.css']
})
export class AddProductComponent implements OnInit {

  @ViewChild("fileUpload", {static: false}) fileUpload: ElementRef;files  = [];  

  addproductForm: FormGroup;
  weightFormGroup: FormGroup;
  descFormGroup: FormGroup;
  imageFormGroup: FormGroup;
  public value;
  public category;
  public sub_category;
  radio = true;
  p_id_saved = false;
  public length : number;
  public data: any;
  items: FormArray;

    selectedFile0 : File;
    selectedFile1 : File;
    selectedFile2 : File;
    selectedFile3 : File;
    selectedFile4 : File;
    selectedFile5 : File;
    selectedFile6 : File;
    fileName1 :any;
    fileName2 :any;
    fileName3 :any;
    fileName4 :any;
    fileName5 :any;
    fileName6 :any;
    public imagePath;
    imgURL: any;
    public message: string;

  p_id=sessionStorage.getItem("p_id");
  photo_doclabel: any;
  showLoader: boolean;

  constructor(private fb: FormBuilder ,public snackbar: MatSnackBar, private adminservice: DefaultAdminService ,private cd: ChangeDetectorRef, private snackBar: MatSnackBar) { }

  preview(files) {
    if (files.length === 0) return;

    var mimeType = files[0].type;
    if (mimeType.match(/image\/*/) == null) {
      this.message = "Only images are supported.";
      return;
    }
    else if (mimeType.match(/image\/*/) != null) {
      this.message = "";
      return;
    }


    var reader = new FileReader();
    this.imagePath = files;
    reader.readAsDataURL(files[0]);
    reader.onload = _event => {
      this.imgURL = reader.result;
    };
  }
  //Primary Image
  onFileChanged0(event){
    this.selectedFile0 = <File>event.target.files[0];
  }
  //Secondary Images

  onFileChanged1(event){

    this.selectedFile1 = <File>event.target.files[0];
    this.fileName1=this.selectedFile1['name'];
  }
  onFileChanged2(event){

    this.selectedFile2 = <File>event.target.files[0];
    this.fileName2=this.selectedFile2['name'];
  }
  onFileChanged3(event){
    this.selectedFile3 = <File>event.target.files[0];
  }
  onFileChanged4(event){
    this.selectedFile4 = <File>event.target.files[0];
  }
  onFileChanged5(event){
    this.selectedFile5 = <File>event.target.files[0];
  }
  onFileChanged6(event){
    this.selectedFile6 = <File>event.target.files[0];
  }



  ngOnInit() {

    this.addproductForm = this.fb.group({

        name:['' ,Validators.required ],
        cat_id:['' ,Validators.required],
        productImg:[''],
        mrp:['' ,Validators.required],
        price:['' ,Validators.required],
        weight:[''],
        description:['']
    // this.photo_doclabel = data["data"][0].productImg;

    });

    this.weightFormGroup = this.fb.group({
      items: this.fb.array([])
    });
    this.descFormGroup = this.fb.group({
      items: this.fb.array([])
    });
    this.imageFormGroup = this.fb.group({
      productImg1:[''],
      productImg2:[''],
      productImg3:[''],
      productImg4:[''],
      productImg5:[''],
      productImg6:[''],





    });
    // this.adminservice.fetch_subcategory(this.category[''].cat_id).subscribe(data=>{
    //   this.sub_category=data['result'];
    //   console.log(this.sub_category);console.log('hello');
    // });


      this.adminservice.show_all_categories().subscribe(data =>{
        this.category = data["result"];
         console.log(this.category );

      });


      // for(let i=0;i<this.category.length;i++){
      //    console.log(this.category[i].cat_name);
      //  }





  }


  // onChange(e){
  //   // let cat_id ;
  //   console.log("hi");
  //   console.log(e);
  //   this.adminservice.fetch_subcategory({cat_id:e}).subscribe(data=>{
  //     this.sub_category=data['result'];
  //     console.log(this.sub_category);
  //     console.log('hello');
  //   });
  // }






  onSubmit()
  {
    this.showLoader = true;
    console.log('Add Product Works!');
    console.log(this.addproductForm.value);
    console.log(this.addproductForm.value.name);
    let formdata = new FormData();
    formdata.append("name",this.addproductForm.value.name);
    formdata.append("cat_id",this.addproductForm.value.cat_id);
    formdata.append("mrp",this.addproductForm.value.mrp);
    formdata.append("price", this.addproductForm.value.price);
    formdata.append("weight", this.addproductForm.value.weight);
    formdata.append("description", this.addproductForm.value.description);
    formdata.append("productImg",this.selectedFile0,this.selectedFile0.name); 
    this.adminservice.add_product(formdata)
    .subscribe(data=> {
      if(data["status"]==1){
      console.log('Success',data);
      this.p_id = data['p_id'];
      sessionStorage.setItem('p_id',this.p_id);
      console.log('product id is ' + this.p_id);
      this.p_id_saved = true;
      this.snackbar.open("Product Added", "OK" ,{
        duration:3000
      });
      this.showLoader=false;
      }else{
        this.snackbar.open("Cannot Add Product" ,"OK",{
          duration:3000
        });
      }

    } ,

    error => console.log('Error',error)
    );

  }


// ----------------------------Product Added-------------------------------
// ============================Add Weight ===================================
  createItem(): FormGroup {
    return this.fb.group({
      weight: [''],
      price:[''],
      p_id : this.p_id
    })
  }

  addItem() {
    this.items = (this.weightFormGroup.get('items') as FormArray);
    this.items.push(this.createItem());
  }
  addWeight(){
  //  let  p_id= sessionStorage.getItem(this.p_id)
    console.log('Adding Weight');
    console.log(this.weightFormGroup.value);
    // let weight = this.weightFormGroup.value;
    // this.data.p_id =this.p_id;
    this.adminservice.add_product_weight(this.weightFormGroup.value)
    .subscribe(data=>
      {
        if(data["status"]==1){
          console.log('Success' , data);
          this.snackbar.open("Product Weight Added","OK",{
            duration:3000
          });
        }else{
          this.snackbar.open("Product Weight Could Not Be Added","OK",{
            duration:3000
          });
        }
      }  , 
    error => console.log('Error',error));
  }
// =============================Weight Added===========================
// =============================Description Add ===========================

  createDesc(){
    return this.fb.group({
      property :[''],
      value :[''],
      p_id : this.p_id
    })
  }
  add_desc(){
    this.items = this.descFormGroup.get('items') as FormArray;
    this.items.push(this.createDesc());
  }

  addProdDesc(){
    console.log('Adding Description');
    console.log(this.descFormGroup.value);
    this.adminservice.add_product_desc(this.descFormGroup.value)
    .subscribe(data=>{
      if(data["status"]==1){
        this.snackbar.open("Product Description Added","OK",{
          duration:3000
        });
        console.log('Success' , data)
      }else{
        this.snackbar.open("Product Description Could Not Be Added","OK",{
          duration:3000
        });
      }
    }  , 
    error => console.log('Error',error));
  }

// =============================Description  Added===========================

// ============================= Add Multiple Images ===========================
**
addAllImages(){
  this.showLoader=true;
  console.log('Add All Images Works!');
      console.log('product id is ' + this.p_id);
      console.log(this.imageFormGroup.value);
    let imagesdata = new FormData();


    imagesdata.append("productImg1",this.selectedFile1, this.selectedFile1['name']  ); 
    imagesdata.append("productImg2",this.selectedFile2 , this.selectedFile2['name'] ); 
    imagesdata.append("productImg3",this.selectedFile3 , this.selectedFile3['name']); 
    imagesdata.append("productImg4",this.selectedFile4,this.selectedFile4['name'] ); 
    imagesdata.append("productImg5",this.selectedFile5 , this.selectedFile5['name'] ); 
    imagesdata.append("productImg6",this.selectedFile6 , this.selectedFile6['name']); 
    imagesdata.append("p_id",this.p_id); 


    this.adminservice.add_product_multiple_images(imagesdata)
    .subscribe(data=> {
      // this.p_id = data['p_id'];
      // sessionStorage.setItem('p_id',this.p_id);
      if(data["status"]==1){
        console.log('Success',data);
      this.p_id = data['p_id'];
      // sessionStorage.setItem('p_id',this.p_id);
      // console.log('product id is ' + this.p_id);
        this.snackbar.open("Product Images Added","OK",{
          duration:3000
        });
        this.showLoader=false;
      }else{
        this.snackbar.open("Product Images Could Not Be Added","OK",{
          duration:3000
        });
      }

    } ,

    error => console.log('Error',error)
    );
  **
}

// ============================= Added Multiple Images ===========================



 }

Функция addAllmages () не вызывается и выдает следующую ошибку: enter image description here

Я попытался отправить изображения, удалив свойство SelectedFile["name"], а затем отправив изображение, но в этом случае все 6 добавляемых мной изображений не сохраняются вместо только одного изображения, т.е. первое изображение сохраняется 6 раз

...