Overview
Cloudinary offers powerful tools for managing and manipulating media assets through its upload parameters. Two key parameters, eval and on_success, allow you to inject custom JavaScript code during different stages of the upload process. This article provides a comprehensive overview of these parameters, their usage, and examples to help you leverage them effectively in your Cloudinary projects.
Eval Parameter
What is Eval?
The eval parameter is used to evaluate and modify upload parameters before the file is uploaded to Cloudinary. It allows you to insert custom JavaScript code to dynamically adjust parameters based on specific conditions related to the uploaded file. This can be done through the upload preset configuration through the Upload manipulation section or through our SDKs.
Key Features
- Modify Upload Parameters: Adjust parameters like tags, contextual metadata, and structured metadata.
- JavaScript Code Execution: Inject up to 4095 characters of JavaScript code.
-
Variables: Utilize resource_info and upload_options within the script.
- resource_info: References the resource info as it would be received in an upload response (e.g., resource_info.width).
- upload_options: Assigns amended upload parameters (e.g., upload_options.tags = "new_tag").
Restrictions
Certain upload options cannot be modified using the `eval` parameter, including eager, eager_async, upload_preset, resource_type, type, and public_id.
Examples
-
Setting Tags Based on Filename
This can be used to automatically tag assets with SKUs, so they can be loaded into our Product Gallery Widget using tags.
Example: Uploaded filename = RV750CA_06, generated tag = RV750CAif (resource_info.filename) {
upload_options['tags'] = resource_info.filename.split('_')[0];
upload_options['unique_filename'] = false;
} -
Tagging Images with Faces
Add a tag to images detected to have faces.if (resource_info.faces) {
upload_options["tags"] = "has_faces";
} -
SDK Example: Conditional Moderation
Set moderation to "manual" for images with a quality analysis focus greater than 0.6.cloudinary.v2.uploader.upload("user_photo.jpg", {
quality_analysis: true,
eval: "if (resource_info.quality_analysis.focus > 0.6)
{ upload_options['moderation'] = 'manual' }"
}).then(result => console.log(result)); -
How not to apply incoming transformation for specific formats, otherwise apply transformation:
if (resource_info.format == "gltf" || resource_info.format == "glb")
{ upload_options['transformation'] = ''}
else { upload_options['transformation'] = 'q_auto:good'} -
How to extract structured metadata from file names
An image called “blackweek_2023.png” → To extract 2023 and to put in the metadata field “Year”.
upload_options["metadata"] = "year="
Here is a screenshot from the upload preset page:
+ resource_info.filename.split('_')[1].split('.')[0];
OnSuccess Parameter
What is OnSuccess?
The on_success parameter allows you to execute custom JavaScript code after a file has been successfully uploaded to Cloudinary. This can be useful for updating the asset with additional metadata, tags, or contextual information based on the results of post-upload processing. This can be done through the upload preset configuration through the Upload manipulation section or through our SDKs.
Key Features
- Post-Upload Execution: Runs JavaScript code after the file upload is complete.
-
Variables: Utilize event (or e) and current_asset within the script.
-
event (or e): Encapsulates incoming data, including upload_info and status.
- upload_info - an object with all the resource info as it would be received in an upload response. For example, e.upload_info?.width returns the width of the uploaded resource.
- status - either 'success' or 'failure'
- current_asset: Provides an update method to modify tags, context, and metadata.
-
event (or e): Encapsulates incoming data, including upload_info and status.
Examples
-
Updating Metadata Based on Filename and Frame Rate
Update metadata fields such as original file name and frame rate based on the upload information.
let filename = e.upload_info.original_filename;
let frame_rate = String(e.upload_info.frame_rate);
if (filename && frame_rate) {
current_asset.update({ metadata: { original_file_name: filename, fps: frame_rate } });
} else if (filename) {
current_asset.update({ metadata: { original_file_name: filename } });
} else if (frame_rate) {
current_asset.update({ metadata: { fps: frame_rate } });
} else {
throw new Error("The file cannot be uploaded");
} -
Setting tags and context based on the filename:
Filename with the structure <SKU_SORT> , for example 14wqas41_31
Result:
tags: 14wqas41, someothertags
contextual metadata: caption: 31
current_asset.update(
{tags: [e.upload_info?.original_filename?.toLowerCase().split('_')[0],
'someothertags'],
context:
{caption: e.upload_info?.original_filename?.toLowerCase().split('_')[1]}})
Here is a screenshot from the upload preset configuration to set the On Success:
-
Setting Tags and Contextual Metadata based on Content Analysis
Update an asset’s contextual metadata with a caption from the Cloudinary AI Content Analysis add-on and add a specific tag.
Here is the JS code to use in the upload preset in the On Success field:
current_asset.update({tags: ['autocaption'],
You can do the same by using one of our SDKs. Here is an example with Node.JS
context: {caption: e.upload_info?.info?.detection?.captioning?.data?.caption}}cloudinary.v2.uploader.upload("user_photo.jpg", {
detection: "captioning",
on_success: "current_asset.update({ tags: ['autocaption'],
context: { caption: e.upload_info?.info?.detection?.captioning?.data?.caption }})"
}).then(result => console.log(result)) - In case, you would like to add the tags in addition to the existing tags, you can use the following code:
current_asset.update({ tags: [...e.upload_info.tags, "autocaption"],
context: {caption: e.upload_info?.info?.detection?.captioning?.data?.caption}}
Conclusion
The eval and on_success parameters in Cloudinary provide robust functionality for customizing and enhancing the upload process through JavaScript. By understanding and utilizing these parameters, you can dynamically adjust upload settings and update asset information based on specific conditions, ensuring more efficient and tailored media management workflows.
For more detailed information and additional examples, please refer to the official Cloudinary documentation on upload parameters.
Comments
0 comments
Please sign in to leave a comment.