I have a problem with uploading a file from my pc via ngForm as part of a small project I do for a class. It seems that I cannot correctly upload the file as during debugging I get "fakedirectory/name-of-file" rather than the actual temp directory. I did already search some related posts but they seem to be different than my case and I cannot get them to work. I would greatly appreciate any help and guidance what can I try next. I have a frontend part of the project and a separate rest api backend. I will paste the related code here:
HTML:
<form #addOfferForm="ngForm" (ngSubmit)="submitNewOffer(addOfferForm)">
Here I have other text inputs that work fine
...
<input (I tried with ngForm and without) type="file" accept="image/png" id="offerPhoto" (change)="handleOfferPhotoUpload($event)">
...
<button class="public">Publish</button>
Component:
offerPhoto?: File
handleOfferPhotoUpload(event: InputEvent){
const input: HTMLInputElement = event.target as HTMLInputElement;
this.offerPhoto = input.files[0]
console.log( "this.offerPhoto" + this.offerPhoto)
}
addOfferForm: FormGroup = new FormGroup({
offerName: new FormControl(''),
...
offerPhoto: new FormControl(''),
})
submitNewOffer(addOfferForm: NgForm): void {
this.offerService.addOffer$( addOfferForm.value).subscribe({
next: (offer) => {
this.router.navigate(['/offers'])
},
error: (error) => {
console.error(error)
}
})
Service:
addOffer$(body: { offerName: string, ... offerPhoto: File }): Observable<IOffer> //This is an interface that I use {
return this.http.post<IOffer>(`${apiUrl}/offers`, body, { withCredentials: true });
}
Then on the backend I have:
function createOffer(req, res, next) {
const { offerName, buyOrSell, cameraOrLens, offerDescription, offerPhoto, offerContact } = req.body;
const { _id: userId } = req.user;
uploadFile(offerPhoto).then(id => {
const offerPhoto = `https://drive.google.com/uc?id=${id}`
return offerModel.create({ offerName, ... offerPhoto, userId })
.then(offer => res.json(offer))
.catch(next);
})
The uploadFile function worked with a simpler form where I just update a photo that is already there but cannot seem to get the image uploaded as part of the form. I am very stuck and don't know what else to try. A very big thanks to anybody who can help me in advance!