Home > Mobile >  How to upload a file using formGroup in angular
How to upload a file using formGroup in angular

Time:06-02

my api works fine, it uploads, edits and deletes images, but my front-end doesn't works, when i try to upload an image it shows me an error, here is my code:

export class CrearProductoComponent implements OnInit {

  productoForm: FormGroup;
  titulo = 'Crear Produto';
  id: string | null;
  uploadedFiles!: File;
  imagen_Form!: any;

  constructor(private fb: FormBuilder, 
              private router: Router, 
              private toastr: ToastrService, 
              private _productoService: ProductoService,
              private aRouter: ActivatedRoute) { 
     this.productoForm = this.fb.group({
       producto: ['', Validators.required],
       categoria: ['', Validators.required],
       ubicacion: ['', Validators.required],
       precio: ['', Validators.required],
       imagen: ['']
     })
     this.id = this.aRouter.snapshot.paramMap.get('id');
  }

  ngOnInit(): void {
    this.esEditar();
  }

  onFileChange(e: any) {
    /*
    const formData = new FormData();
    this.uploadedFiles = e.target.files
    const file = e.target.files
    */
    if (e.target.files.length > 0) {
      const file = e.target.files[0];
      this.uploadedFiles = file;
    }
    /*
    formData.append('imagen', file);
    this.productoForm.patchValue({ imagen: formData });
    this.productoForm.updateValueAndValidity();
    */

  }

  agregarProducto(){
    console.log(this.productoForm);
    console.log(this.productoForm.get('producto')?.value);

    const PRODUCTO: Producto = {
      nombre: this.productoForm.get('producto')?.value,
      categoria: this.productoForm.get('categoria')?.value,
      ubicacion: this.productoForm.get('ubicacion')?.value,
      precio: this.productoForm.get('precio')?.value,
      imagen: this.uploadedFiles
    };

    if(this.id !== null){
      this._productoService.actualizarProducto(PRODUCTO, this.id).subscribe(data => {
        this.toastr.success('Producto actualizado', 'Producto actualizado');
        this.router.navigate(['/']);
      }, error => {
        console.log(error);
      })
    } else {
      console.log(PRODUCTO);
      this._productoService.guardarProducto(PRODUCTO).subscribe(data => {
        this.toastr.success('El producto fue registrado con exito!', 'Producto Registrado');
        this.router.navigate(['/']);
      }, error => {
        console.log(error);
        this.productoForm.reset();
      })
    }
  }

  esEditar(){
      if(this.id !== null){
        this.titulo = 'Editar Producto';
        this._productoService.obtenerProducto(this.id).subscribe(data => {
          this.productoForm.setValue({
            producto: data.nombre,
            categoria: data.categoria,
            ubicacion: data.ubicacion,
            precio: data.precio
          })
        })
      }
  }

}

i have visit many pages and still not getting an answer or a guide, i could do it with formData, but is there any method to do it with a class model and formGroup?

also this my error

error

error 2

it worked in postman but not in my front-end.

CodePudding user response:

You have to send the request body as formData if it includes files.

let objFormData = new FormData();
objFormData.append('producto', this.productoForm.get('producto')?.value)
...
objFormData.append('imagen', fileToUpload);
....
this._productoService.guardarProducto(objFormData).subscribe(data => {
...

CodePudding user response:

How to upload a file using formGroup in angular ==>

Definitely you need to pass selected files through formdata and need to use direct httpclient

import { HttpClient } from '@angular/common/http';


constructor(public http: HttpClient) { }

upload(event:any){
   const formData = new FormData();
   formData.append("image", event.files[0]);
   this.http.post("api", formData).subscribe((res: any) => {
      ....
   })
}
  • Related