'Angular posts an undefined file to nestjs controller
I'm trying to upload a file from an Angular app to a nestjs backend but the controller gets an undefined file. This is the Angular file service:
async create(file: File): Promise<string> {
// With console.log I can see file is defined
// file comes directly from the input file (event.target.files[0])
const formData: FormData = new FormData();
formData.append('file', file);
let headers = new HttpHeaders();
headers = headers
.set(
'Content-Type',
`multipart/form-data; boundary=-----${guid.v4()}`
)
.set('Accept', 'application/json');
return await this.http.post<string>('/api/files', formData, { headers }).toPromise();
}
And this the controller method:
@Post()
@UseInterceptors(FileInterceptor('file'))
async create(@UploadedFile() file: any) {
return await this.files.create(file.buffer);
}
The http interceptor says: TypeError: Cannot read property 'buffer' of undefined.
I tried to upload files with postman and it works, I guess I am missing something in my angular code.
Solution 1:[1]
Try something like this is your create() function:
return this.http.patch<any>(
`${this.domain}/users/avatar/upload/${id}`,
formData,
{
headers: new HttpHeaders()
.set("Accept", "application/json") // <=== there is the point
}
);
this worked for me.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | hkthiet99 |
