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 *ngIf="changeImage">
<div >
<div >
<!--Preview-->
<div *ngIf="filePath && filePath !== ''">
<img [src]="filePath" [alt]="uploadForm.value.name" >
</div>
<div >
<h5 >{{fileName}}</h5>
<p >Upload preview. Dont forget to save it.:)</p>
<button type="submit" *ngIf="imagePreviewUploaded">Save</button>
<a *ngIf="uploadedTries == 0" href="javascript:void(0)" (click)="file.click()" >
Upload
</a>
<a *ngIf="uploadedTries > 0" href="javascript:void(0)" (click)="file.click()" >
Upload Diffrent image
</a>
<input type="file"
#file
[multiple]="false"
(change)="imagePreview($event)"
style="display:none" />
<button (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);
}
CodePudding user response:
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);
}