Home » c# » How send image as byte array from Angular 9 to C# Web API Core, like are property of object? CRUD Client aplication with image

How send image as byte array from Angular 9 to C# Web API Core, like are property of object? CRUD Client aplication with image

Posted by: admin February 21, 2020 Leave a comment

Questions:

Frontend – Angular 9

Backend – ASP.NET Core Web API
/\
Middleware Entity Framework 6.0
/
MS SQL SERVER

1. I don’t know what type of object property I must set in Angular?

2. How I can add an image to my object and send them to Web Api?

3. How I can show them back in Angular app.?

Web API Controller POST:

    [HttpPost]
    public async Task<ActionResult<Leaks>> PostLeaks(Leaks leaks)
    {
        // DateTime and Username implemented to backend
        DateTime curDate = DateTime.Now;
        leaks.Date = curDate;

        var currentUser = HttpContext.User;
        string userLastname = currentUser.Claims.FirstOrDefault(c => c.Type == "lastname").Value;
        leaks.Repairer = userLastname;
        //
        _context.Leaks.Add(leaks);
        await _context.SaveChangesAsync();

        return CreatedAtAction("GetLeaks", new { id = leaks.Id }, leaks);
    }

Leaks.cs:

public partial class Leaks
{
    public int Id { get; set; }
    public string Sn { get; set; }
    public string ShiftSmt { get; set; }
    public string ShiftMi { get; set; }
    public string Location { get; set; }
    public DateTime? Date { get; set; }
    public string Repairer { get; set; }
    public string AoiResult { get; set; }
    public string OperatorSmt { get; set; }
    public string ModelSmt { get; set; }
    public string Platform { get; set; }
    public string Remark { get; set; }
    public string Defect { get; set; }
    public byte[] Image { get; set; }
    public string Status { get; set; }
    public string Side { get; set; }
    public string Extra1 { get; set; }
    public string Extra2 { get; set; }
}

MS SQL Image data type is varbinary(MAX)

Leaks.component.ts:

  // *ngOnInit start
  ngOnInit() {
  //Selected options loader
  this.platformsService.getAllPlatforms()
  .subscribe(res => this.platforms = res as []);

  this.defectslistService.getAllDefectslist()
  .subscribe(res => this.defect = res as []);

  // input form validation
  this.leaksForm = this.formbulider.group({ 
    Date:[null],
    Sn:[null, [Validators.required]],
    ShiftMI:[null, [Validators.required]],
    ShiftSMT:[null, [Validators.required]],
    Location:[null, [Validators.required]],
    Defect:[null, [Validators.required]],
    Side:[null, [Validators.required]],
    AoiResult:[null],
    Platform:[null, [Validators.required]],
    ModelSMT:[null],
    OperatorSMT:[null],
    Repairer:[null],
    Image:[null],
    Remark:[null],
    Status:[null, [Validators.required]],
  });
  // *load all data from Database*
  this.loadallLeaks();
  this.toastr.info("Init Successfully Done");

  //*Angular mat-table*
  this.leaksService.getAllLeaks().subscribe(list => {
      let array = list.map(item => {
        return { ...item };
      });
      this.listData = new MatTableDataSource(array);
      this.listData.sort = this.sort;
      this.listData.paginator = this.paginator;
      this.isLoading = false;
    });
  //*Angular mat-table end*

  }
  // *ngOnInit end*

  loadallLeaks() {

  this.allLeaks = this.leaksService.getAllLeaks();

  this.leaksService.getAllLeaks().subscribe(res => {
    this.dataSource = new MatTableDataSource(res);
  })

  this.toastr.info("Data Was Successfully Loaded");
  }

  onFormSubmit() {
  this.dataSaved = false;
  const leaks = this.leaksForm.value; 
  this.CreateLeaks(leaks);
  this.leaksForm.reset();
  }

  loadLeaksToEdit(leaksId: string) {

  this.leaksService.getLeaksById('/'+leaksId).subscribe(leaks=> {
  this.massage = null;
  this.dataSaved = false;
  this.leaksIdUpdate = leaks.Id;
  this.leaksForm.controls['Sn'].setValue(leaks.Sn);
  this.leaksForm.controls['Date'].setValue(leaks.Date);
  this.leaksForm.controls['ShiftSMT'].setValue(leaks.ShiftSMT); 
  this.leaksForm.controls['ShiftMI'].setValue(leaks.ShiftSMT); 
  this.leaksForm.controls['Location'].setValue(leaks.Location);
  this.leaksForm.controls['Defect'].setValue(leaks.Defect);
  this.leaksForm.controls['Side'].setValue(leaks.Side);
  this.leaksForm.controls['AoiResult'].setValue(leaks.AoiResult);
  this.leaksForm.controls['Platform'].setValue(leaks.Platform);
  this.leaksForm.controls['ModelSMT'].setValue(leaks.ModelSMT);
  this.leaksForm.controls['OperatorSMT'].setValue(leaks.OperatorSMT);
  this.leaksForm.controls['Remark'].setValue(leaks.Remark);
  this.leaksForm.controls['Repairer'].setValue(leaks.Repairer);
  this.leaksForm.controls['Image'].setValue(leaks.Image);
  this.leaksForm.controls['Status'].setValue(leaks.Status);

  });

  }

  CreateLeaks(leaks: Leaks) {
  if (this.leaksIdUpdate == null) {
    this.leaksService.createLeaks(leaks).subscribe(
    () => {
    this.dataSaved = true;
    this.toastr.success("Record Saved Successfully");
    this.loadallLeaks();
    this.leaksIdUpdate = null;
    this.leaksForm.reset();
  } );
  } else {
    leaks.Id = this.leaksIdUpdate;
    this.leaksService.updateLeaks(leaks).subscribe(() => {
    this.dataSaved = true;
    this.toastr.success("Record Updated Successfully");
    this.loadallLeaks();
    this.leaksIdUpdate = null;
    this.leaksForm.reset();
  }); }
  } 
  deleteLeaks(leaksId: string) {
  if (confirm("Are you sure you want to delete this ?")) { 
    this.leaksService.deleteLeaksById(leaksId).subscribe(() => {
    this.dataSaved = true;
    this.toastr.warning("Record Deleted Succefully"); 
    this.loadallLeaks();
    this.leaksIdUpdate = null;
    this.leaksForm.reset();
  }); }
  }
  resetForm() {
  this.leaksForm.reset();
  this.massage = null;
  this.dataSaved = false;
  this.toastr.info("Form Succefully reseted");
  }

leaks.ts:

export class Leaks {
Id:number;
Date:string;
Sn:string;
ShiftMI:string;
ShiftSMT:string;
Location:string;
Defect:string;
Side:string;
AoiResult:string;
Platform:string;
ModelSMT:string;
OperatorSMT:string;
Repairer:string;
Image:[];
Remark:string;
Status:string;
}

Big thanks!

How to&Answers: