I am a beginner in Angular and I am having trouble uploading an image from Angular as I encounter 4 errors:
1) Error in the post method: Cannot find name 'formData'. Did you mean 'FormData'?ts(2552)
2) Error in the subscribe method: const headers: HttpHeaders
No overload matches this call.
Overload 1 of 5,
3) Error in the subscribe method:Cannot find name 'file'. Did you mean 'File'?ts(2552)
4) Error in this.url: Type 'string | ArrayBuffer' is not assignable to type
'string'.
Type 'ArrayBuffer' is not assignable to type 'string'
Below, I have provided the code snippet.
public imagePath;
constructor(private http: HttpClient) { }
url: string;
ngOnInit() {
}
onSelectFile(event)
{ // called each time file input changes
if (event.target.files && event.target.files[0])
{
var reader = new FileReader();
this.imagePath = event.target.files;
for (const file of this.imagePath)
{
const formData = new FormData();
formData.append('image', file, file.name);
}
const headers = new HttpHeaders();
headers.append('Content-Type', 'multipart/form-data');
headers.append('Accept', 'application/json');
this.http.post('http://localhost/imageupload.php', formData).subscribe( headers, console.log(file.name) );
reader.readAsDataURL(event.target.files[0]); // read file as data url
reader.onload = (event) => { // called once readAsDataURL is completed
this.url = event.target.result;
}
}
}