1

I am new in Angular, I am trying to upload image from angular but getting 4 errors:

1)in post method: Cannot find name 'formData'. Did you mean 'FormData'?ts(2552)
2)In subscribe method: const headers: HttpHeaders
No overload matches this call.
Overload 1 of 5,
3) In subscribe method:Cannot find name 'file'. Did you mean 'File'?ts(2552)
4) In this.url: Type 'string | ArrayBuffer' is not assignable to type
'string'.
Type 'ArrayBuffer' is not assignable to type 'string'

Below i am attaching code.

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;

      }
    }
  }

1 Answer 1

0

Constants are block-scoped, you do not have the access constant from the outer scope (for is a block-scoped)

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, { headers }).subscribe(response => console.log(response));

          reader.readAsDataURL(event.target.files[0]); // read file as data url

          reader.onload = (event) => { // called once readAsDataURL is completed
          this.url = event.target.result;
        }
      }
    }
  }
Sign up to request clarification or add additional context in comments.

1 Comment

But still error in subscribe method in headers, and on this.url

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.