1

I'm facing this error when I upload a product from Angular with it's image to NestJs Server,this error pops up.As you can see in the below screen shot, there is the uploaded product with image path,and also there's some error. I don't know which part/end generating this error.

enter image description here

Angular side code. From here the image is getting selected and uploaded alongside other properties

  async addfile() {
    let formData = new FormData();
    formData.set(
      'file',
      this.AddbookForm.value.coverimage,
      this.AddbookForm.value.coverimage.name
    );
    this.http
      .post('http://localhost:3000/images/upload', formData)
      .subscribe((res) => {});
  }
  async addbooks() {
    (await this.apiService.addbooks(this.AddbookForm.value)).subscribe(
      (res) => {
        console.log(res);
      }
    );
  }

  async uploadimage(event: any) {
    this.AddbookForm.value.coverimage = event.target.files[0];
    console.log('file', this.AddbookForm.value.coverimage);
  }
}
M Nouman
  • 437
  • 1
  • 5
  • 22

2 Answers2

1

Angular HttpClient expects a JSON response per default. It will always try to parse the response body as a JSON and will fail if it is not. Please check the response body and set the response type accordingly.

Example:

this.http.post('http://localhost:3000/images/upload', formData, { responseType: 'text' })

Or, of course, you could let your server respond with a JSON. I am not familiar with NestJs, but I guess it would be enough to return an object:

return cb(null, { createdFile: `${filename}${extname(file.originalname)}` });
MoxxiManagarm
  • 8,735
  • 3
  • 14
  • 43
  • Thanks that `responsetype` worked. I'm not getting the unexpected token error. But one thing I wanna ask, sometimes when I upload a product It uploads the image to server, but the path does not get attached to the product, it misses the path mapping. why is that? any clue? or does I need statemanagment or something? – M Nouman Jul 25 '22 at 18:19
0

try this, let me know if it not works.

async uploadimage(event: any) {
    event.target.files[0].title = 'file';
    this.AddbookForm.value.coverimage = event.target.files[0];
    console.log('file', this.AddbookForm.value.coverimage);
  }
Prashant Singh
  • 611
  • 1
  • 5
  • 14
  • `ERROR Error: Uncaught (in promise): TypeError: Failed to execute 'set' on 'FormData': parameter 2 is not of type 'Blob'. TypeError: Failed to execute 'set' on 'FormData': parameter 2 is not of type 'Blob'. at adbooks.component.ts:37:14` . This is the error I'm getting in google console. The book is getting uploaded without image. – M Nouman Jul 25 '22 at 17:53
  • You are not passing blob to second param as error says. – Prashant Singh Jul 26 '22 at 14:27