[SOLVED] Angular – Upload image to API

Issue

I have an API that takes an image and saves it to my drive. It works fine when I use Postman. However when I try to call the API from my Angular service nothing happens. What must I change to be able to upload the image? Thank you.

Here is my component:

onSaveFile(e) {

  this.imagePreviewUploaded = false;
  this.changeImage = false;
  this.fileName = "";

  var image = this.uploadForm.get('img').value;
  const formData: FormData = new FormData();
  formData.append('formFile', image);

  this.generalService.uploadGeneralConfigurationLogo(formData);

  this.filePath = defaultImage;
  this.uploadedTries = 0;
  this.toastr.success("Success", "The image has been uploaded!")

}

Here is my form to upload the image:

<form [formGroup]="uploadForm" (ngSubmit)="onSaveFile($event)">

  <div class="row" *ngIf="changeImage">
    <div class="col-sm-12 align-items-center">
      <div class="card">
        <!--Preview-->
        <div *ngIf="filePath && filePath !== ''">
          <img [src]="filePath" [alt]="uploadForm.value.name" class="avatar">
        </div>
        <div class="card-body">
          <h5 class="card-title">{{fileName}}</h5>
          <p class="card-text">Upload preview. Dont forget to save it.:)</p>
          <button type="submit" class="btn btn-primary" *ngIf="imagePreviewUploaded">Save</button>
          <a *ngIf="uploadedTries == 0" href="javascript:void(0)" (click)="file.click()" class="btn btn-primary">
            Upload
          </a>
          <a *ngIf="uploadedTries > 0" href="javascript:void(0)" (click)="file.click()" class="btn btn-primary">
            Upload Diffrent image
          </a>

          <input type="file"
                 #file
                 [multiple]="false"
                 (change)="imagePreview($event)"
                 style="display:none" />
          <button class="btn btn-secondary" (click)="onCancelFileUpload($event)">Cancel</button>
        </div>
      </div>
    </div>
  </div>

</form>

Here is my Angular service method to upload image:

uploadGeneralConfigurationLogo(formFile) {
  return this.http.post<GeneralConfiguration>(this.baseUrl + 'generalConfiguration', formFile, { headers: { 'Content-Type': undefined }  })
}

Here is my API:

[HttpPost]
public async Task<IActionResult> UploadFile([FromForm] IFormFile formFile)
{
    if (formFile.Length > 0)
    {
        var filePath = Path.GetTempFileName();

        using (var stream = System.IO.File.Create("c:/images/logo.png"))
        {
            await formFile.CopyToAsync(stream);
        }
    }

    return Ok(true);
}

Solution

You need to subscribe the observable in order to submit the request to API.

An Observable instance begins publishing values only when someone subscribes to it. You subscribe by calling the subscribe() method of the instance, passing an observer object to receive the notifications.

onSaveFile(e) {

  ...

  this.generalService.uploadGeneralConfigurationLogo(formData).subscribe(
    next: () => {
      // TO-DO Handle success scenario
    },
    error: (err: Error) => {
      // TO-DO Handle error scenario
    }
  );
}

As you are returning the boolean result from the UploadFile API method, the uploadGeneralConfigurationLogo method should return the (observer) value of the bool type.

uploadGeneralConfigurationLogo(formFile): Observable<bool> {
  return this.http.post<bool>(this.baseUrl + 'generalConfiguration', formFile);
}

Answered By – Yong Shun

Answer Checked By – Timothy Miller (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *