Send a binary file via Angular HttpClient
Asked Answered
S

2

7

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
    ....
Sagunto answered 17/1, 2018 at 8:22 Comment(0)
S
19

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)}
    )
Sagunto answered 17/1, 2018 at 9:8 Comment(1)
Thanks for the solution (y)Hatred
Y
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)
  }
)
Yves answered 4/9, 2020 at 12:37 Comment(4)
thanks, it's made my day, it's perfect if request Header has Content-Type: multipart/form-data; boundary=<calculated when request is sent>Gauleiter
formData.append("myfile", formData) should be formData.append("myfile", file)? Also, http.post(url, body) should have url as the first argument?Fluent
why about a binary data with octet-stream type content insted of formdataCopepod
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.Shuler

© 2022 - 2024 — McMap. All rights reserved.