Ayush Gupta
Ayush Gupta

Reputation: 9295

Upload images from Angular4 to Cloudinary

I am new to cloudinary and Angular4.

I have been looking for a way to upload image to cloudinary via Angular4, but have not beeen able to find any documentation for it. The documentations I found pertain to image transformations rather than upload.

How can I upload the image to cloudinary from Angular4.

PS. I am using Angular4 AOT

Upvotes: 1

Views: 1515

Answers (1)

Eitan Peer
Eitan Peer

Reputation: 4345

You can find an example here. It is using ng2-file-upload which works well with Angular4 as well.

The main point to consider is wiring the uploader to your Cloudinary account -

// Create the file uploader, wire it to upload to your account
const uploaderOptions: FileUploaderOptions = {
  url: `https://api.cloudinary.com/v1_1/${this.cloudinary.config().cloud_name}/upload`,
  // Upload files automatically upon addition to upload queue
  autoUpload: true,
  // Use xhrTransport in favor of iframeTransport
  isHTML5: true,
  // Calculate progress independently for each uploaded file
  removeAfterUpload: true,
  // XHR request headers
  headers: [
    {
      name: 'X-Requested-With',
      value: 'XMLHttpRequest'
    }
  ]
};
this.uploader = new FileUploader(uploaderOptions);

this.uploader.onBuildItemForm = (fileItem: any, form: FormData): any => {
  // Add Cloudinary's unsigned upload preset to the upload form
  form.append('upload_preset', this.cloudinary.config().upload_preset);
  // Add built-in and custom tags for displaying the uploaded photo in the list
  let tags = 'myphotoalbum';
  if (this.title) {
    form.append('context', `photo=${this.title}`);
    tags = `myphotoalbum,${this.title}`;
  }
  form.append('tags', tags);
  form.append('file', fileItem);

  // Use default "withCredentials" value for CORS requests
  fileItem.withCredentials = false;
  return { fileItem, form };
};

Upvotes: 1

Related Questions