.NET image and video upload

Cloudinary provides an API for uploading images, videos, and any other kind of file to the cloud. Files uploaded to Cloudinary are stored safely in the cloud with secure backups and revision history. Cloudinary's APIs allow secure uploading from your servers, directly from your visitors' browsers or mobile applications, or fetched via remote public URLs.

Cloudinary's .NET SDK wraps Cloudinary's upload API and simplifies the integration. .NET methods are available for easily performing .NET image and video uploads to the cloud and .NET helper methods are available for uploading directly from a browser to Cloudinary.

This page covers common usage patterns for .NET image and video upload with Cloudinary.

For details on all available upload options and parameters, see the Media upload documentation, and the Upload method of the Upload API Reference.

Upload widget

Cloudinary's Upload widget is an interactive, feature rich, simple-to-integrate user interface that enables you to add Cloudinary upload support to your website. The widget can be easily embedded in your web application with just a few lines of JavaScript code, eliminating the need to develop in-house interactive upload capabilities. See the Upload widget documentation for detailed information.

Server-side upload

You can upload images, videos, or any other raw file to Cloudinary from your .NET code. Uploading is done over HTTPS using a secure protocol based on your account's api_key and api_secret parameters.

.NET image upload

The following C# method uploads an image to the cloud:

Copy to clipboard
public ImageUploadResult Upload(ImageUploadParams parameters);

The ImageUploadParams class sets an image to upload with additional parameters and ImageUploadResult class provides the deserialized server response.

For example, uploading a local image file named 'my_image.jpg':

In C#:

Copy to clipboard
var uploadParams = new ImageUploadParams()
{
    File = new FileDescription(@"c:\my_image.jpg")
};
var uploadResult = cloudinary.Upload(uploadParams);

In VB.NET:

Copy to clipboard
Dim uploadParams = New ImageUploadParams
uploadParams.File = New FileDescription("c:\my_image.jpg")
Dim uploadResult = m_cloudinary.Upload(uploadParams)

For a full list of the Upload method parameters, see the Upload method in the Upload API reference.

.NET video upload

You upload videos in exactly the same way as images. However, the Upload method supports uploading files up to 100 MB only. To upload larger videos, use the UploadLarge method, which uploads large files to the cloud in chunks.

The UploadLarge method has the identical signature and options as the Upload method, with the addition of an optional ChunkSize parameter (default 20 MB).

The following example uploads dog.mp4 to Cloudinary and stores it in a bi-level folder structure with the public ID dog_closeup. It also performs two eager transformations that resize the video to a square and a small rectangle.

Copy to clipboard
var uploadParams = new VideoUploadParams()
{
  File = new FileDescription(@"dog.mp4"),
  PublicId = "my_folder/my_sub_folder/dog_closeup",
  EagerTransforms = new List<Transformation>()
  {
    new Transformation().Width(300).Height(300).Crop("pad").AudioCodec("none"),
    new Transformation().Width(160).Height(100).Crop("crop").Gravity("south").AudioCodec("none")),
  }
  EagerAsync = true,
  EagerNotificationUrl = "https://mysite.example.com/my_notification_endpoint"
};
var uploadResult = cloudinary.Upload(uploadParams);

Upload response

By default, uploading is performed synchronously. Once finished, the uploaded image is immediately available for manipulation and delivery. You can also perform an asynchronous upload using the UploadAsync method. See Asynchronous API methods for more information.

An upload call returns a JSON object with content similar to the following:

Copy to clipboard
RESPONSE (ImageUploadResult):
{
    "public_id":"tquyfignx5bxcbsupr6a",
    "version":1375302801,
    "signature":"52ecf23eeb987b3b5a72fa4ade51b1c7a1426a97",
    "width":1920,
    "height":1200,
    "format":"jpg",
    "resource_type":"image",
    "created_at":"2017-07-31T20:33:21Z",
    "bytes":737633,
    "type":"upload",
    "url":
        "https://res.cloudinary.com/demo/image/upload/v1375302801/tquyfignx5bxcbsupr6a.jpg",
    "secure_url":
        "https://res.cloudinary.com/demo/image/upload/v1375302801/tquyfignx5bxcbsupr6a.jpg"
}

The response includes HTTP and HTTPS URLs for accessing the uploaded media asset as well as additional information regarding the uploaded asset: The Public ID, resource type, width and height, file format, file size in bytes, a signature for verifying the response and more.

Related topics

  • For more information on uploading media assets, see the Media upload documentation.
  • For details on all available upload parameters, see the Upload method of the Upload API Reference.

Direct uploading from the browser

The upload samples mentioned above allows your server-side .NET code to upload images to Cloudinary. In this flow, if you have a web form that allows your users to upload images, the image data is first sent to your server and only then uploaded to Cloudinary. A more efficient and powerful option is to allow your users to upload images directly from the browser to Cloudinary instead of going through your servers. This method allows for faster uploading and better user experience. It also reduces load from your servers and reduces the complexity of your .NET applications.

Tip
For a full working example, see the Photo Album sample project.

Uploading directly from the browser is done using Cloudinary's jQuery plugin. To ensure that all uploads are authorized by your application, a secure signature must first be generated in your server-side .NET code. You can use the SignParameters method to generate the signature:

Copy to clipboard
cloudinary.Api.SignParameters(IDictionary<string, object> parameters);

Direct uploading environment setup

Start by including the required Javascript files - jQuery, Cloudinary's plugin and the jQuery-File-Upload plugin it depends on. These are available in the js folder of Cloudinary's Javascript library.

For your convenience we have prepared a PowerShell script that can download necessary files for you. Windows PowerShell is shipped with all Microsoft Windows operation systems since Windows 7, but could be installed on earlier systems as well. By default, the feature of script execution is disabled in the Windows PowerShell. To enable it, execute the following command (you should have administrator rights):

Copy to clipboard
set-executionpolicy remotesigned

Then you can execute the script (assuming you are in the script directory):

Copy to clipboard
.\get_cloudinary_js.ps1

This command downloads all necessary files to two sub-directories of the current directory - Scripts and Content. If you want to override the destination directory (for example, if you already have a project of a ASP.NET web site), you could pass the destination directory as an argument:

Copy to clipboard
.\get_cloudinary_js.ps1 c:\my_site

Then you can directly include the Javascript files:

Copy to clipboard
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="jquery.ui.widget.js"></script>
<script type="text/javascript" src="jquery.iframe-transport.js"></script>
<script type="text/javascript" src="jquery.fileupload.js"></script>
<script type="text/javascript" src="jquery.cloudinary.js"></script>

Cloudinary's jQuery plugin requires your cloud_name and additional configuration parameters.

Important
Never expose your api_secret in public client-side code.

To set up Cloudinary's configuration, include the following line in your scripts section of a view:

Copy to clipboard
<script>
    $.cloudinary.config("cloud_name", "your_cloud_name");
</script>

Alternatively, you can use the GetCloudinaryJsConfig method of the Cloudinary class from your view code to add necessary JS code. All necessary configuration options will be taken from your instance of Cloudinary class. For example:

Copy to clipboard
@Model.Cloudinary.GetCloudinaryJsConfig()

You can override the location of JS files and include additional jQuery files that are required for more advanced uploading options:

Copy to clipboard
@Model.Cloudinary.GetCloudinaryJsConfig(
    true, @"https://your-local-host.domain/cloudinary_js/")

This is equivalent to:

Copy to clipboard
<script src="https://your-local-host.domain/cloudinary_js/jquery.ui.widget.js"></script>
<script src="https://your-local-host.domain/cloudinary_js/jquery.iframe-transport.js"></script>
<script src="https://your-local-host.domain/cloudinary_js/jquery.fileupload.js"></script>
<script src="https://your-local-host.domain/cloudinary_js/jquery.cloudinary.js"></script>
<script src="https://your-local-host.domain/cloudinary_js/canvas-to-blob.min.js"></script>
<script src="https://your-local-host.domain/cloudinary_js/jquery.fileupload-image.js"></script>
<script src="https://your-local-host.domain/cloudinary_js/jquery.fileupload-process.js"></script>
<script src="https://your-local-host.domain/cloudinary_js/jquery.fileupload-validate.js"></script>
<script src="https://your-local-host.domain/cloudinary_js/load-image.all.min.js"></script>
<script type='text/javascript'>
  $.cloudinary.config({
    "cloud_name": "your_cloud_name",
    "api_key": "your_api_key",
    "private_cdn": false,
    "cdn_subdomain": false
);
</script>

The Cloudinary jQuery library utilizes the Blueimp File Upload library to support uploading media directly from the browser. You must explicitly initialize this library:

Copy to clipboard
$(function() {
    if($.fn.cloudinary_fileupload !== undefined) {
        $("input.cloudinary-fileupload[type=file]").cloudinary_fileupload();
    }
});

Direct uploading from the browser is performed using XHR (Ajax XMLHttpRequest) CORS (Cross Origin Resource Sharing) requests. In order to support older browsers that do not support CORS, the jQuery plugin will gracefully degrade to an iframe based solution.

This solution assumes placing cloudinary_cors.html in the public folder of your .NET application, for example ~/Content. This file is required for iframe fallback upload and is available in the html folder of Cloudinary's Javascript library.

This file can be downloaded using the powershell script of get_cloudinary_js.ps1.

The following code builds a URL of the local cloudinary_cors.html file:

Copy to clipboard
 string cors_location = (new UriBuilder(Request.Url.AbsoluteUri)
     { Path = Url.Content("~/Content/cloudinary_cors.html") }).ToString();

Direct upload file tag

Embed a file input tag in your HTML pages using the BuildUploadForm method of the Api class.

The following example adds a file input field to your form. Selecting or dragging a file to this input field will automatically initiate uploading from the browser to Cloudinary.

Copy to clipboard
<form>
    @Model.Cloudinary.Api.BuildUploadForm("image_id", "auto",
        new SortedDictionary<string, object>() { { "callback", cors_location } },
        null)
</form>

When uploading is completed, the identifier of the uploaded image is set as the value of a hidden input field of your selected name (e.g., 'image_id' in the example above).

You can then process the identifier received by your .NET controller and store it in your model for future use, exactly as if you're using a standard server side uploading.

The following .NET controller code shows how to process the received response:

Copy to clipboard
[HttpPost]
[AcceptVerbs(HttpVerbs.Post)]
public void UploadDirect()
{
    var headers = HttpContext.Request.Headers;
    string content = null;
    using (StreamReader reader = new StreamReader(HttpContext.Request.InputStream))
    {
        content = reader.ReadToEnd();
    }
    if (String.IsNullOrEmpty(content)) return;

    Dictionary<string, string> results = new Dictionary<string, string>();
    string[] pairs = content.Split(new char[] { '&' }, 
        StringSplitOptions.RemoveEmptyEntries);

    foreach (var pair in pairs)
    {
        string[] splittedPair = pair.Split('=');
        results.Add(splittedPair[0], splittedPair[1]);
    }

    Photo photo = new Photo()
    {
        Bytes = Int32.Parse(results["bytes"]),
        CreatedAt = DateTime.ParseExact(HttpUtility.UrlDecode(results["created_at"]), 
        "yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture),
        Format = results["format"],
        Height = Int32.Parse(results["height"]),
        Path = results["path"],
        PublicId = results["public_id"],
        ResourceType = results["resource_type"],
        SecureUrl = results["secure_url"],
        Signature = results["signature"],
        Type = results["type"],
        Url = results["url"],
        Version = Int32.Parse(results["version"]),
        Width = Int32.Parse(results["width"]),
    };

Having stored the image_id, you can now display a directly uploaded image in the same way you would display any other Cloudinary hosted image:

Copy to clipboard
@Model.Cloudinary.Api.UrlImgUp.Format("jpg").Transform(
    new Transformation().Width(120).Height(80).Crop("fill")).BuildUrl(Model.Photo.PublicId)

Additional direct uploading options

When uploading directly from the browser, you can still specify all the upload options available to server-side uploading.

For example, the following call performs direct uploading that will also tag the uploaded image, limit its size to given dimensions and generate a thumbnail eagerly. Also notice the custom HTML attributes.

Copy to clipboard
<form>
    @Model.Cloudinary.Api.BuildUploadForm("image_id", "auto",
          new SortedDictionary<string, object>()
          {
            { "callback", cors_location },
            { "tags", "directly_uploaded" },
            { "crop", "limit" },
            { "width", 1000 },
            { "height", 1000 },
            { "eager", new Dictionary<string,object>() 
              {{ "crop","fill" }, { "width",150 }, { "height", 100 } }}
          },
          new Dictionary<string, string>() { { "style", "margin-top: 30px" } })
</form>

For the full list of parameters available for signed uploads, see the Upload method in the Upload API reference.

Note
For security reasons, only this limited set of parameters can be used in an unsigned upload request.

Directly uploading a video

Client-side upload from the browser (signed upload)

The following example renders a direct file upload input field using the BuildUploadForm helper method. Although the default resource_type for this method is auto, the video type is explicitly defined, and asynchronous eager transformations are used to generate adaptive bitrate streaming content. The html parameter is used to include standard HTML parameters (in this case, an id attribute) in the generated tag.

Note
This example assumes you have already included and configured the JQuery files as described in Direct uploading from the browser.

Copy to clipboard
string input = m_cloudinary.Api.BuildUploadForm("video_id", "video",
    new Dictionary<string, object>() {
        { "eager", "sp_full_hd/83u8"},
        { "eager_async", true },
        { "eager_notification_url", "https://mysite.example.com/notify_endpoint" }
    },
    new Dictionary<string, string>() {
        { "id", "my_upload_tag" }
    }
);

Client-side upload from the browser (unsigned upload)

The following example renders an unsigned direct file upload input field using the BuildUnsignedUploadForm helper method. The default resource_type for this method is auto, so it can be used for images, video, and raw files. The method defines a public ID and tags for the uploaded file.

Note
This example assumes you have already included and configured the JQuery files as described in Direct uploading from the browser. It also assumes that my_upload_preset is defined as an unsigned preset for your account.

Copy to clipboard
string input = m_cloudinary.Api.BuildUnsignedUploadForm("video_id", "my_upload_preset", null,
    new Dictionary<string, object>() {
        { "public_id", "my_video" },
        { "tags", "user_218,screencast" }
    }, null
);

Additional jQuery library features

Cloudinary's jQuery library also enables an enhanced uploading experience with options like showing a progress bar, displaying a thumbnail of the uploaded image, drag & drop support, uploading multiple files and more.

For example, bind to Cloudinary's cloudinarydone event if you want to be notified when an upload to Cloudinary has completed. You will have access to the full details of the uploaded image and you can display a cloud-generated thumbnail of the uploaded images using Cloudinary's jQuery plugin. The following code creates a 150x100 thumbnail of an uploaded image and updates an input field with the public ID of this image.

Copy to clipboard
$('.cloudinary-fileupload').bind('cloudinarydone', function(e, data) {  
  $('.preview').html(
    $.cloudinary.image(data.result.public_id, 
      { format: data.result.format, version: data.result.version, 
        crop: 'fill', width: 150, height: 100 })
  );    
  $('.image_public_id').val(data.result.public_id);    
  return true;
});

You can find more details and options in the jQuery documentation.

Related topics

  • For more information on uploading media assets, see the Media upload documentation.
  • For details on all available upload parameters, see the Upload method of the Upload API Reference.

✔️ Feedback sent!