Cloudinary Blog

Angular Image Upload

Angular Image Upload with Cloudinary

Based on Typescript and a total revamp of AngularJS, Angular is an open-source framework for developing mobile and web apps. That framework has been gaining popularity over the years with a large developer following.

Uploading Angular images to Cloudinary triggers this process:

  • The app’s UI, i.e., its client side, picks up the image files through a form control or component.
  • The app’s server side collects, transforms, and saves the files in the cloud.

How to spur those two activities? By means of an HTML template along with an Angular-image upload component. See the tutorial below.

Angular Image Uploads

Enabling Angular image uploads to Cloudinary takes two steps.

Step 1: Set Up an HTML Template

First, place an image upload component in your app for your users by doing either of the following:

  • Specify, in HTML, the HTML5 file’s input type by adding the code below to the app.component.html file:

    Copy to clipboard
    <div>
    <form action="" method="post" enctype="multipart/form-data">
        <input type="file">
    </form>
    <label>Choose file</label>
    </div>
  • Type the following npm command to install the Angular image-upload component ng2-file-upload:

    Copy to clipboard
    npm install ng2-file-upload --save
    • Next, add the related parameters to the app.component.html file by attaching the Angular image-upload component to the HTML markup:

      • For multiple uploads
      Copy to clipboard
      `<input type="file" ng2FileSelect [uploader]="uploader" multiple  />`
      • For single uploads
      Copy to clipboard
      `<input type="file" ng2FileSelect [uploader]="uploader" />`
      `<button [disabled]="loading" (click)="upload()" class="btn">Upload</button>`
      `_app.component.html_`

Step 2: Create an Angular Image Upload Component

First, install the Angular Image Upload Cloudinary library that works for Angular 5, 6, and 7 with this npm command:

Copy to clipboard
npm install @cloudinary/angular-5.x --save

Afterwards, add the code below to the src/app/app.component.ts file to build an Angular image-upload component:

Copy to clipboard
import { Component, OnInit, Input } from '@angular/core';
import { FileUploader, FileUploaderOptions, ParsedResponseHeaders } from 'ng2-file-upload';
import { Cloudinary } from '@cloudinary/angular-5.x';

@Component({
  selector: 'app-list',
  templateUrl: 'app.component.html'
})
export class ImageUploadComponent implements OnInit {

  @Input()
  responses: Array<any>;

  private hasBaseDropZoneOver: boolean = false;
  private uploader: FileUploader;
  private title: string;

  constructor(
    private cloudinary: Cloudinary,
    private zone: NgZone,
    private http: HttpClient
  ) {
    this.responses = [];
    this.title = '';
  }

  ngOnInit(): void {
    // 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 unsigned upload preset to the upload form
      form.append('upload_preset', this.cloudinary.config().upload_preset);

      // Add file to upload
      form.append('file', fileItem);

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


  fileOverBase(e: any): void {
    this.hasBaseDropZoneOver = e;
  }
}
_upload.component.ts_

Note
Replace the variable cloud_ name in the code above with your account’s cloud name as displayed on your Cloudinary Dashboard.

The ImageUpload component in the code processes the uploaded files through the ng2-file-upload component, subsequently uploading them to Cloudinary.

Remarkably, such a setup eliminates the tedious chore of developing a back-end API to receive files from the front end and to validate and process them before storing them in Cloudinary. As soon as a user has uploaded a file, Cloudinary seamlessly handles the remaining tasks that culminate in the file being stored in the Media Library.

For the complete code of the above process, see this comprehensive GitHub repository.

AngularJS Image Uploads

For app developers who are on AngularJS, follow the steps below to upload AngularJS files.

First, install the Cloudinary AngularJS SDK and the ng-file-upload library with this npm command:

Copy to clipboard
bower install ng-file-upload cloudinary_ng --save

Next, define CloudinaryProvider in your app’s configuration file with this code:

Copy to clipboard
yourApp.config(['cloudinaryProvider', function (cloudinaryProvider) {
  cloudinaryProvider
      .set("cloud_name", "good")
      .set("secure", true)
      .set("upload_preset", "my_preset");
}]);

Note
Replace the variable cloud_ name with your account’s cloud name as displayed on your Cloudinary Dashboard.

Finally, attach an uploadFiles function in your app to the controller $scope with, for example, this code:

Copy to clipboard
$scope.uploadFiles = function(files){
  $scope.files = files;
  angular.forEach(files, function(file){
    if (file && !file.$error) {
      file.upload = $upload.upload({
        url: "https://api.cloudinary.com/v1_1/" + cloudinary.config().cloud_name + "/upload",
        data: {
          upload_preset: cloudinary.config().upload_preset,
          context: 'image=' + $scope.title,
          file: file
        }
      }).progress(function (e) {
        file.progress = Math.round((e.loaded * 100.0) / e.total);
        file.status = "Uploading... " + file.progress + "%";
      }).success(function (data, status, headers, config) {
        $rootScope.list = $rootScope.list || [];
        data.context = {custom: {image: $scope.title}};
        file.result = data;
        $rootScope.photos.push(data);
      }).error(function (data, status, headers, config) {
        file.result = data;
      });
    }
  });
};

The $upload.upload function uploads all the files straight to Cloudinary.

Manipulate and Deliver Uploaded Angular Or AngularJS Files

Cloudinary’s Angular SDK contains several out-of-the-box components that enable you to manipulate, optimize, and deliver images in the best format. Add those components to your Angular app.

Afterwards, specify the attributes and values that you desire for the parameters for the <cl-image> component, for example:

Copy to clipboard
<cl-image public-id="dog" angle="20" format="jpg">
    <cl-transformation height="150" width="150" crop="fill" effect="sepia"></cl-transformation>
    <cl-transformation overlay="text:arial_20:Angular" color="#EECCAA" gravity="south" y="20"></cl-transformation>
</cl-image>

In the above code, the value of public-id (dog) is the name of the image stored in Cloudinary.

To manipulate and transform images and files as you desire, simply embed the <cl-transformation> component within <cl-image>. For details of the many options available, see the related Cloudinary documentation. You’ll be amazed at the wealth of choices at your fingertips and the marvelous effects generated by the manipulation and transformation tasks. Do give it a whirl!

Recent Blog Posts

Our $2B Valuation

By
Blackstone Growth Invests in Cloudinary

When we started our journey in 2012, we were looking to improve our lives as developers by making it easier for us to handle the arduous tasks of handling images and videos in our code. That initial line of developer code has evolved into a full suite of media experience solutions driven by a mission that gradually revealed itself over the course of the past 10 years: help companies unleash the full potential of their media to create the most engaging visual experiences.

Read more
Direct-to-Consumer E-Commerce Requires Compelling Visual Experiences

When brands like you adopt a direct–to-consumer (DTC) e-commerce approach with no involvement of retailers or marketplaces, you gain direct and timely insight into evolving shopping behaviors. Accordingly, you can accommodate shoppers’ preferences by continually adjusting your product offering and interspersing the shopping journey with moments of excitement and intrigue. Opportunities abound for you to cultivate engaging customer relationships.

Read more
Automatically Translating Videos for an International Audience

No matter your business focus—public service, B2B integration, recruitment—multimedia, in particular video, is remarkably effective in communicating with the audience. Before, making video accessible to diverse viewers involved tasks galore, such as eliciting the service of production studios to manually dub, transcribe, and add subtitles. Those operations were costly and slow, especially for globally destined content.

Read more
Cloudinary Helps Minted Manage Its Image-Generation Pipeline at Scale

Shoppers return time and again to Minted’s global online community of independent artists and designers because they know they can count on unique, statement-making products of the highest quality there. Concurrently, the visual imagery on Minted.com must do justice to the designs into which the creators have poured their hearts and souls. For Minted’s VP of Engineering David Lien, “Because we are a premium brand, we need to ensure that every single one of our product images matches the selected configuration exactly. For example, if you pick an 18x24 art print on blue canvas, we will show that exact combination on the hero images in the PDF.”

Read more
Highlights on ImageCon 2021 and a Preview of ImageCon 2022

New year, same trend! Visual media will continue to play a monumental role in driving online conversions. To keep up with visual-experience trends and best practices, Cloudinary holds an annual conference called ImageCon, a one-of-a-kind event that helps attendees create the most engaging visual experiences possible.

Read more