0

I'm sending images and other form data through multi-part requests. When I call the api using PostMan the image is successfully adding. But I;m getting an error from back-end when I call the same API using angular code.

enter image description here

Component.ts

addOffer() {
    this.formData = new FormData();
    this.formData.append('promotion', this.file, this.file.name);
    this.formData.append("main_text", this.offerAddForm.controls['title'].value);
    this.formData.append("type", '1');
    this.formData.append("footer_text", 'rdy');

    this._addOfferService.addOffer(this.formData)
      .pipe(first())
        .subscribe(
            data => {
              console.log("Yo yo "+data);
            },
            error => {
              console.log("An Error Occurred add notify ", error);
            });
  }

Service.ts

addOffer(formData) {
    const token = this.authService.getToken();
    let headerOptions = new HttpHeaders({
      'Content-Type': 'multipart/form-data',
      'Authorization': 'Bearer '+token
    });

    const url = environment.baseURL + 'promotions';
    return this.http.post<any>(url, formData, {headers: headerOptions})
      .pipe(map(response => {
        return response;
      }));
  }

Update: Error From back-end:

An invalid promotion type.

Request Payload :

enter image description here

enter image description here

What I'm doing wrong here ?

ONE_FE
  • 968
  • 3
  • 19
  • 39

2 Answers2

0
 let urlSearchParams = new URLSearchParams();
    urlSearchParams.append('cc', this.PayElement.CC);

    // alert(urlSearchParams.toString());
    this.appService.sendToOtherService('https://dddddd?ggg=dfdf&ddgg=5555, 
      urlSearchParams.toString()).then(res2 => {
//

    }).catch(res3 => {
     //
    });



sendToOtherService(url: string, data: any): Promise<any> {
    let headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded'});
    let options = new RequestOptions({headers: headers});
    return this.http.post(url, data, options).toPromise()
      .then(response => response.json() as any)
      .catch(this.handleError);
  }
user1882196
  • 129
  • 2
  • 8
0

In Html

    <div>
    <input hidden id="input-file-id" (change)="sendFile($event)" type="file" />
<label for="input-file-id" class="btn btn-warning ">
<img class="mr-3" src="assets/images/choose_file.png" alt="cloud"> Choose
                                        Files</label>
<p style="color: tomato;">{{isErr}}</p>
<div class="row col-md-12 mt-3 ml-0 pt-4 pb-4" style="border: 2px solid #fbbc04">
<div class="col-md-9" id="wrap">
<span>{{ fileName }}</span>
<audio id="buzzer" controls>
<source [src]="audioSrc" id="wav_src" type="audio/wav" />
<source [src]="audioSrc" type="audio/mpeg" />
    Your browser does not support the audio element.
    </audio>
    </div>
    </div>
    </div>

In controller/component

sendFile(event) {

this.isErr='';
let fileList: FileList = event.target.files;
if (fileList.length > 0) {
  let file: File = fileList[0];
  console.log(file);
  console.log(file.name);
  this.fileName = file.name;
  this.fileSize = file.size;
  this.audioSrc = URL.createObjectURL(file);
  $("#buzzer").attr("src", this.audioSrc);
  this.yourServiceObj.sendAudioService(file)
    .subscribe(data => {
      this.serviceResponse = data;
    },
      error => {
        this.isErr='Something went wrong! Please try after sometime';
      });
}
}

In Service

sendAudioService(blob) {
this.apiUrl = 'your api url';
var data = new FormData();
data.append("audio", blob);

return this.http.post(this.apiUrl, data, {responseType: 'text'})
  .pipe(map(response => {
    return response;
  }));
}
Talha
  • 1
  • 3
  • @Lalinda Sampath, I think you are not sending "this.file" correctly. You have not specified from where you are getting it. – Talha Feb 04 '20 at 11:43