Upload file on Cloudinary with flutter.

Snehal Masalkar
Jul 27 · 2 min read

To upload files on Cloudinary we need “Upload- preset” from Cloudinary, and for that, we have to create an account on Cloudinary. Upload preset contains 'CLOUD_NAME' and 'UPLOAD_PRESET'.

When you logged in to Cloudinary we can get 'CLOUD_NAME' on dashboard for 'UPLOAD_PRESET' follow the following path in your account and you will get upload preset.

Click on Settings > Click on Upload > Scroll down to Upload presets.

For file uploading on Cloudinary with flutter, we have to add the ‘cloudinary_public’ plugin in our project in ‘pubspec.yaml’ file.

dependencies:
cloudinary_public: ^0.8.2

After that, we have to run the command ‘flutter pub get’ in the terminal.

Now in your Dart code, you can use:

import 'package:cloudinary_public/cloudinary_public.dart';
  1. To upload a file, we have to pick the file first, and for that, we can use a file picker plugin.
  2. Add plugin dependencies in “pubspec.yaml” file.
  3. Use command on terminal “flutter pub get”.
  4. To pick a file we can use the following function.
static Future<CloudinaryResponse> selectFile(
) async {
CloudinaryResponse response;
try {
var result = await FilePicker.platform.pickFiles(
type: FileType.any,
allowMultiple: true,
);

if (result != null) {
for (PlatformFile file in result.files) {
if (file.path != null) {
response = await uploadFileOnCloudinary(
filePath: file.path,
resourceType: CloudinaryResourceType.Auto,
);
}
}

}
} on PlatformException catch (e, s) {
} on Exception catch (e, s) {
}
return response;
}

5. File picker function required 2 parameters

  1. 1.Type i.e file type and
  2. “allowMultiple” i.e boolean type value, true or false.

6. Result contain single or multiple files of type PlatformFile, if there are multiple files then we can upload them one by one otherwise, a single file can be uploaded.

7. So my “uploadFileOnCloudinary” function looks like this.

static Future<CloudinaryResponse> uploadFileOnCloudinary(
{String filePath, CloudinaryResourceType resourceType}) async {
String result;
CloudinaryResponse response;
try {
var cloudinary = CloudinaryPublic('CLOUD_NAME', 'UPLOAD_PRESET', cache: false);
response = await cloudinary.uploadFile(
CloudinaryFile.fromFile(filePath, resourceType: resourceType),
);
} on CloudinaryException catch (e, s) {
print(e.message);
print(e.request);
}
return response;
}

This function will return a response of “CloudinaryResponse” and the response contains secureUrl.

CloudinaryResponse contains

  1. assetId
  2. createdAt
  3. fromCache
  4. originalFileName
  5. publicId
  6. secureUrl
  7. tags
  8. url

We can use secureUrl to display the file. Using Cloudinary’s upload capabilities, you can upload media assets in bulk with a variety of options for customizing how they will be uploaded, including naming.

In this way, we can upload files on Cloudinary