8

I want to send an http POST request with a binary data from a file. I get a successful server respond when I do it via postman->Body->Binary->Choose file. see image:

enter image description here

But I can not figure out how to do it via Angular HttpClient. How can I finish the following:

set processImage(event) {
    console.log(event);
    let files: FileList = event.target.files;
    let file = files[0]; 
    //send the file as a binary via httpClient
    ....

2 Answers 2

20

Finally got it to work. Here's the code for future reference for anyone in need:

processImage(event) {
    console.log(event);
    let files: FileList = event.target.files;
    let file : File = files[0];
    this.http.post(URL, file).subscribe(
      (r)=>{console.log('got r', r)}
    )
Sign up to request clarification or add additional context in comments.

Comments

0

For Sending binary Data in Angular you can use FormData example :

let file = event.target.files[0];
let url = 'your url';
let formData = new FormData();
formData.append("myfile", file);

this.http.post(url,formData).subscribe(
  (res) => {
    console.log('response', res)
  }
)

4 Comments

thanks, it's made my day, it's perfect if request Header has Content-Type: multipart/form-data; boundary=<calculated when request is sent>
formData.append("myfile", formData) should be formData.append("myfile", file)? Also, http.post(url, body) should have url as the first argument?
why about a binary data with octet-stream type content insted of formdata
This is precisely incorrect. Sending binary is totally different than sending form data, which requires at least one key/value pair. For example, when uploading to S3 using a presigned URL you must send in binary and this will not work. You can simply look at Postman and notice they are totally different bodies.

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.