klp
klp

Reputation: 153

How to post data to server in Angular2?

onChange(event) {
    var image = event.srcElement.files;
    console.log(image);

My console value is

FileList {0: File, length: 1}

What should I send to server as my post data?

Upvotes: 2

Views: 4240

Answers (2)

martin
martin

Reputation: 96969

I assume the event.srcElement is in fact <input type="file"> since you're accessing it's files property which is available only of file input fields.

Angular2 Http service works only with string bodies as of now. There's an opened issue to support also FormData which would simplify things a lot.

See feat(http): Support many types of body on Request/Response and all ConnectionBackend implementations.

Right now, you could use raw XMLHttpRequest object wrapped with NgZone to send the POST data as FormData.

However, maybe even easier solution for you would be to send the file as base64 encoded string:

onChange(event) {
    var image = event.srcElement.files[0];
    var reader = new FileReader();
    reader.onload = (evt) => {
        // Print base64 encoded file content
        console.log(evt.target.result);
        // Send data to server
        this.http.post(url, evt.target.result)...
    }
    reader.readAsDataURL(image);
}

For more info see:

Upvotes: 1

Alexis Le Gal
Alexis Le Gal

Reputation: 337

Something like :

return this.http
      .post(this.heroesUrl, JSON.stringify({name: name}), {headers: this.headers})
      .toPromise()
      .then(res => res.json().data)
      .catch(this.handleError);

is perfect, you have everything you need at https://angular.io/docs/ts/latest/tutorial/toh-pt6.html

Upvotes: 0

Related Questions