2

So, I have to send a file (or files) together with other json data.

From what I've searched, I can only send files alone or convert them to base64 and then send the json with the base64 code to the API (not confirmed).

Is there another way to send files that is not converting them to base64?

We already had a problem with base64 and images where our GET was taking a lifetime to load because of the length of the base64 strings.

EDIT: So, I just tried to send it as base64 and it worked, so, it works, I just want to avoid send it that way.

Elydasian
  • 2,016
  • 5
  • 23
  • 41
user64324
  • 21
  • 3
  • I finally found a proper way to upload a file and send some JSON within the same request and made a proper answer here: https://stackoverflow.com/questions/39693966/how-to-angular2-post-json-data-and-files-in-same-request/47408232#47408232 – maxime1992 Nov 21 '17 at 08:18

1 Answers1

0

you need add image data in the form like this.

<form (submit)="submit(formData)" #formData="ngForm">
  <div class="form-group">
    <label for="name">Product Name:</label><input type='text' name='name' class="form-control" id="name" ngModel>
  </div>
<div class="form-group">
    <label for="image">Image:</label><input type="file" name='image' class="form-control" id="image" ngModel>
  </div>

<button type="submit" class="btn btn-default">Add</button>
</form> 

component

submit(formData){
    let inputEl: HTMLInputElement = this.el.nativeElement.querySelector('#image');   
           let fileCount: number = inputEl.files.length;   
            let formData = new FormData();  
            if (fileCount > 0) {
                    formData.append('image', inputEl.files.item(0));
             }

// Now call your service.

    }

this is pseudo code but you can add image in the form data and send to backend. otherwise you can make two post request one for form data and another for the image.

CharanRoot
  • 6,181
  • 2
  • 27
  • 45