How to send file parameter to Cloudinary post request in angular2

757 views Asked by At

I am uploading image file to cloudinary with their image upload API. I am implementing it like this,

Html code

<input type="file" ng2FileSelect [uploader]="uploader"/>
<button class="btn btn-primary" (click)="uploadImages()">Upload</button>

Typescript Code

  public uploader: FileUploader = new FileUploader({});

  uploadImages() {
    const params = this.createUploadParams();
    this.upload(params)
      .subscribe(data => {
        console.log("response", data);
      })
  }

  private createUploadParams() {
    return {
      file: this.uploader.queue[0].file,
      upload_preset: env.CLOUDINARY_UPLOAD_PRESET,
      pulic_id: 'PUBLIC_ID'
    }
  }

  upload(params) {
    return this.http.post(`${this.apiLink}/image/upload`, JSON.stringify(params))
      .map(data => data);
  }

But it is giving me the following error

"{"error":{"message":"Missing required parameter - file"}}

I am using ng2-file-upload to upload the files in angular2.

1

There are 1 answers

0
Eitan Peer On

You need to add the file and upload preset thru a FormData object, and add headers to the request as follows:

Import Http and Headers from @angular/http:

import { Http, Headers } from '@angular/http';

Update the code that uploads the files:

uploadImages() {
  const params = this.createUploadParams();
  this.upload(params)
    .subscribe(data => {
      console.log('response', data);
    });
}

private createUploadParams() {
  let formData: FormData = new FormData();
  formData.append('upload_preset', env.CLOUDINARY_UPLOAD_PRESET);
  formData.append('file', this.uploader.queue[0]._file);
  return formData;
}

upload(params) {
  let headers = new Headers();
  headers.append('X-Requested-With', 'XMLHttpRequest');
  return this.http.post(`${this.apiLink}/upload`, params, {headers})
  .map(data => data);
}

You can find an additional example of using ng2-file-upload here