2
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?

2 Answers 2

1

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:

Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

that ok but in my case an empty object is been sent
toPromise() send an asynchronous object, so you have to protect your code until the data are actually send

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.