Giter VIP home page Giter VIP logo

konstantinkai / uploadcare_client Goto Github PK

View Code? Open in Web Editor NEW
20.0 3.0 7.0 812 KB

A flutter library for working with Uploadcare REST API. File uploads, media processing, and adaptive delivery for web and mobile.

Home Page: https://pub.dev/packages/uploadcare_client

License: BSD 3-Clause "New" or "Revised" License

Dart 98.10% Kotlin 0.04% Ruby 0.82% Swift 0.39% Objective-C 0.01% HTML 0.06% Shell 0.40% Dockerfile 0.17%
flutter dart uploadcare uploadcare-api flutter-uploadcare-client flutter-package file-upload file-distribution upload-images upload-videos

uploadcare_client's Introduction

build

Uploadcare client for Dart/Flutter

Uploadcare is a complete file handling platform that helps you ship products faster and focus on your business goals, not files. With Uploadcare, you can build infrastructure, optimize content, conversions, load times, traffic, and user experience. Read more...

A dart/flutter library for working with Uploadcare REST API. File uploads, media processing, and adaptive delivery for web and mobile.

Features

Note about uploadcare_flutter package

The uploadcare_flutter package introduced a few extensions for the base package (Dimensions, Offsets, FaceRect, FacesEntityExtension), UploadcareImageProvider. If you don't need these features, you can use uploadcare_client directly

Installation

Dart:

dart pub add uploadcare_client # or uploadcare_flutter

Flutter:

flutter pub add uploadcare_client # or uploadcare_flutter

Create an client

final client = UploadcareClient.withSimpleAuth(
  publicKey: 'puplic_key',
  apiVersion: 'v0.7',
);

UploadcareClient has following API sections

final ApiUpload upload;
final ApiFiles files;
final ApiGroups groups;
final ApiDocumentConverting documentConverting;
final ApiVideoEncoding videoEncoding;
final ApiAddons addons;
final ApiWebhooks webhooks;
final ApiProject project;

You can use each API section separately, for example:

final options = ClientOptions(
  authorizationScheme: AuthSchemeRegular(
    apiVersion: 'v0.7',
    publicKey: 'public_key',
    privateKey: 'private_key',
  )
);

final upload = ApiUpload(options: options);
final fileId = await upload.base(UCFile(File('...some/file')));
// ...etc.

Upload

Base upload

/// For small files
final fileId = await client.upload.base(UCFile(File('path/to/small_file')));

Chunked upload

/// For large files
/// You can manage the number of concurrent requests by setting `ClientOptions.maxConcurrentChunkRequests` field.
final fileId = await client.upload.multipart(UCFile(File('path/to/large_file')));

From url

final fileId = await client.upload.fromUrl('https://files.st/path_to_file');

Auto

/// Auto method accepts small/large/url files as a parameter and calls the necessary method for upload
final fileId1 = await client.upload.auto(UCFile(File('path/to/small_file')));
final fileId2 = await client.upload.auto(UCFile(File('path/to/large_file')));
final fileId3 = await client.upload.auto('https://files.st/path_to_file');

Isolate

/// Also files can be uploaded in dart `isolate`
/// You can manage the number of isolates by setting `ClientOptions.maxIsolatePoolSize` field.
///
/// NOTE: Doesn't work in web environment
final fileId = await client.upload.auto(UCFile(File('path/to/file')), runInIsolate: true);

Progress tracking

/// Also you can track upload progress, all methods accept `onProgress` callback for this
final fileId = await client.upload.(auto|base|multipart|fromUrl)(UCFile(File('path/to/file')), onProgress: (progress) => print(progress));

Cancellable

/// All upload processes can be canceled with `CancelToken`
final cancelToken = CancelToken();

Timer(Duration(seconds: 1), cancelToken.cancel);

try {
  final fileId = await client.upload.auto(UCFile(File('/some/file')), cancelToken: cancelToken);
} on CancelUploadException catch (e) {
  // cancelled
}

Signed upload

Official documentation

/// For signed upload you should provide the project's private key
final client = UploadcareClient(options: ClientOptions(
  authorizationScheme: AuthSchemeRegular(
    publicKey: 'public_key',
    privateKey: 'private_key',
    apiVersion: 'v0.7',
  ),
  useSignedUploads: true,

  /// Optionally you can customize signature lifetime for signed uploads via the `signedUploadsSignatureLifetime` property (default: 30 minutes)
));

/// Now, all your uploads will be signed
await client.uploads.(base|multipart|fromUrl|auto)(UCFile(File('path/to/file')));

Image and file transformations

Official documentation

final cropedCdnImage = CdnImage('<image-uuid>')..transform(CropTransformation(ascpectRatio: AspectRatio(9, 16)));

/// Use the following field for the croped image
/// cropedCdnImage.url;

final cropedAndInlined = CdnImage('<image-uuid>')..transformAll([
  CropTransformation(ascpectRatio: AspectRatio(9, 16)),
  InlineTransformation(true);
]);

/// Use the following field to download the croped image
/// cropedAndInlined.url

If you use uploadcare_flutter you can specify the provider for the Image widget

final image = Image(
  image: UploadcareImageProvider(
    '<image-uuid>',
    transformations: [
      ImageResizeTransformation(
          const Dimensions.fromHeight(1000)),
    ],
),

Full list of image processing operations

Compression:

Operation Type
Format ImageFormatTransformation
Quality, SmartCompression QualityTransformation
Progressive JPEG ProgressiveTransformation
Meta information control StripMetaTransformation

Resize, Crop, Rotate:

Operation Type
Preview PreviewTransformation
Resize, Smart resize ImageResizeTransformation
Crop, Crop by ratio, Crop by objects CropTransformation
Scale crop, Smart crop ScaleCropTransformation
Border radius and circle crop BorderRadiusTransformation
Set fill color SetFillTransformation
Zoom objects ZoomObjectTransformation
Automatic rotation, EXIF-based AutoRotateTransformation
Manual rotation RotateTransformation
Flip FlipTransformation
Mirror MirrorTransformation

Overlays and watermarks:

Operation Type
Image overlay, Self overlay OverlayTransformation
Text overlay TextOverlayTransformation

Effects and enhancements:

Operation Type
Color adjustment Color(Brightness|Exposure|Gamma|Contrast|Sauration|Vibrance|Warmth)Transformation
Enhance EnhanceTransformation
Grayscale GrayscaleTransformation
Inverting InvertTransformation
Conversion to sRGB SrgbTransformation
ICC profile size threshold MaxIccSizeTransformation
Photo filters FilterTransformation
Blur BlurTransformation
Blur region, Blur faces BlurRegionTransformation
Unsharp masking UnsharpMaskingTransformation
Sharpen SharpTransformation

Rasterization:

Operation Type
Rasterization RasterizeTransformation

Gif to video:

Operation Type
Gif to video GifToVideoTransformation
final file = CdnFile('<gif-uuid>')
  ..transform(GifToVideoTransformation([
    VideoFormatTransformation(VideoFormatTValue.Mp4),
    QualityTransformation(QualityTValue.Best),
  ]));

/// Use `file.url` to get video link

Non-image specific operations:

Operation Type
Get file info as JSON JsonFileInfoTransformation
Get file info as application/javascript JsonpFileInfoTransformation
Show or download InlineTransformation
Change filename ChangeFilenameTransformation

Face detection:

Official documentation

/// Detect faces for the image
final FacesEntity entity = await client.files.getFacesEntity('<image-uuid>');

Files

Get file info

/// Get info about the file
final FileInfoEntity file = await client.files.file('<file-uuid>');

/// To get extended file data use `FilesIncludeFields include` field
final FileInfoEntity file = await client.files.file(
  '<file-uuid>',
  include: FilesIncludeFields.withAppData(), /// shortcut for `FilesIncludeFields(predefined: const [FilesIncludeFieldsValue.AppData])`
);

Get list of files

/// Get list of files with default params (offset 0, limit 100, ordered by upload time)
final ListEntity<FileInfoEntity> list = await client.files.list();

Remove files

/// Remove files by the list of ids
await client.files.remove(['<file-uuid>', '<file-uuid>']);

Store files

/// Store files by the list of ids
await client.files.store(['<file-uuid>', '<file-uuid>']);

Metadata

/// Retrieve all metadata values of the file
final Map<String, String> metadata = await client.files.getFileMetadata('<file-uuid>');

/// Retrieve the metadata value of the file for the specific metadata key
final String value = await client.files.getFileMetadataValue('<file-uuid>', '<metadata-key>');

/// Update the metadata value of the file for the specific metadata metadata-key
final String updatedValue = await client.files.updateFileMetadataValue('<file-uuid>', '<metadata-key>', '<new-value>');

/// Delete the metadata value of the file for the specific metadata key
await client.files.deleteFileMetadataValue('<file-uuid>', '<metadata-key>');

Create file copies

/// Copy original files or their modified versions to a default storage
final FileInfoEntity copiedFile = await client.files.copyToLocalStorage('<file-uuid>', metadata: {'<metadata-key>': '<metadata-value>'});

/// Copy original files or their modified versions to a custom storage
final String remoteFileUrl = await client.files.copyToRemoteStorage(file: '<file-uuid>', target: '<remote-storage>');

Groups

/// Create a group of files
final GroupInfoEntity group = await client.groups.create({
  /// Without transformation
  '<image-uuid>': [],

  /// With list of transformations
  '<image-uuid>': [RotateTransformation(90)]
});

/// Retrieve group info
final GroupInfoEntity group = await client.groups.group('<group-uuid>');

/// Store all files in the group
await client.groups.storeFiles('<group-uuid>');

/// Retrieve list of groups
final ListEntity<GroupInfoEntity> list = await client.groups.list();

/// Delete the group by id
await client.groups.delete('<group-uuid>');

Download group as an archive

final group = CdnGroup('<group-uuid>')
  ..transform(ArchiveTransformation(ArchiveTValue.Tar, 'archive.tar'));

/// Use the following field for download the group as archive `group.url`

Video processing

Official documentation

/// Create a task for processing uploaded video files
final ConvertEntity<VideoEncodingResultEntity> result = await client.videoEncoding.process({
  '<video-file-uuid>': [
    /// Cut video from 10 to 40 seconds
    CutTransformation(
      const Duration(seconds: 10),
      length: const Duration(
        seconds: 30,
      ),
    )
  ],
  '<video-file-uuid>': [
    /// Change video resolution
    VideoResizeTransformation(const Size(512, 384)),
    /// Generate 10 thumbnails for the video
    VideoThumbsGenerateTransformation(10),
  ],
});

/// Checks processing status for the task
final Stream<ConvertJobEntity<VideoEncodingResultEntity>> processingStream = client.videoEncoding.statusAsStream(
  result.results.first.token,
  checkInterval: const Duration(seconds: 2),
)..listen((ConvertJobEntity<VideoEncodingResultEntity> status) {
  // do something
});

Document conversion

Official documentation

/// Create a task for processing uploaded document files
final ConvertEntity<DocumentConvertingResultEntity> result = client.documentConverting.process({
  '<document-file-uuid>': [
    /// Convert document to pdf
    DocumentFormatTransformation(DucumentOutFormatTValue.PDF),
  ],
  '<document-file-uuid>': [
    /// Converts the 10th page of the document
    DocumentFormatTransformation(DucumentOutFormatTValue.PNG, page: 10),
  ],
});

/// Checks processing status for the task
final Stream<ConvertJobEntity<DocumentConvertingResultEntity>> processingStream = client.documentConverting.statusAsStream(
  result.results.first.token,
  checkInterval: const Duration(seconds: 2),
)..listen((ConvertJobEntity<DocumentConvertingResultEntity> status) {
  // do something
});

Addons

Object recognition

Official documentation

final taskId = await client.addons.executeAWSRekognition('<image-uuid>');

final result = await client.addons.checkAWSRekognitionExecutionStatus(taskId);

if (result.status == AddonExecutionStatusValue.Done) {
  /// Retrieve file info with appdata fields
  final file = await client.files.file('<image-uuid>', include: FilesIncludeFields.withAppData());

  /// Now you can access recognition info with the following field
  final recognitionData = file.appData.awsRecognition;
}

Malware protection

Official documentation

final taskId = await client.addons.executeClamAV('<file-uuid>');

final result = await client.addons.checkClamAVExecutionStatus(taskId);

if (result.status == AddonExecutionStatusValue.Done) {
  /// Retrieve file info with appdata fields
  final file = await client.files.file('<file-uuid>', include: FilesIncludeFields.withAppData());

  /// Now you can access clamAV result with the following field
  final clamAVData = file.appData.clamAV;
}

Background removal

Official documentation

final taskId = await client.addons.executeRemoveBg('<image-uuid>');

final result = await client.addons.checkRemoveBgExecutionStatus(taskId);

if (result.status == AddonExecutionStatusValue.Done) {
  /// Retrieve file info with appdata fields
  final file = await client.files.file('<image-uuid>', include: FilesIncludeFields.withAppData());

  /// Now you can access removeBg result with the following field
  final removeBgData = file.appData.removeBg;
}

Webhooks

Official documentation

/// Get list of project webhooks
final List<WebhookEntity> hooks = await client.webhooks.list();

/// Create webhook
final WebhookEntity webhook = await client.webhooks.create(targetUrl: '<webhook-endpoint>', event: WebhookEvent.Uploaded);

/// Update webhook
final WebhookEntity webhook = await client.webhooks.update(hookId: '<webhook-id>', isActive: false);

/// Delete webhook
await client.webhooks.delete('<webhook-endpoint>');

Project

/// Get project common information
final ProjectEntity info = await client.project.info();

FAQ

Do you like the package? Buy me a coffee :)

Buy Me A Coffee

uploadcare_client's People

Contributors

bautrukevich avatar konstantinkai avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

uploadcare_client's Issues

Upload images on web

Do you have a guide on how to work with images uploaded from browser? Browsers doesn't have access to the file system as on mobile platforms.

image

In advance thanks!

Can't build web version of app on Heroku

Hi Konstantin

I have this super strange error when I build the web version of the Flutter app on Heroku, and I can't make sense of it. Just in case you immediately see what's wrong, it would be great to know.

I'm using Flutter version 3.0.5

And in advance thanks!

-----> Using buildpacks:
       1. https://github.com/EE/heroku-buildpack-flutter-light
       2. https://github.com/heroku/heroku-buildpack-static.git
-----> https://github.com/EE/heroku-buildpack-flutter-light app detected
-----> Installing SDK from Github repository.
-----> Restoring pub.dev dependencies from CACHE
-----> Enabling Web support
Downloading Linux x64 Dart SDK from Flutter engine e85ea0e79c6d894c120cda4ee8ee10fe6745e187...
         % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                        Dload  Upload   Total   Spent    Left  Speed
       
Building flutter tool...
       
         ╔════════════════════════════════════════════════════════════════════════════╗
         ║                 Welcome to Flutter! - https://flutter.dev                  ║
         ║                                                                            ║
         ║ The Flutter tool uses Google Analytics to anonymously report feature usage ║
         ║ statistics and basic crash reports. This data is used to help improve      ║
         ║ Flutter tools over time.                                                   ║
         ║                                                                            ║
         ║ Flutter tool analytics are not sent on the very first run. To disable      ║
         ║ reporting, type 'flutter config --no-analytics'. To display the current    ║
         ║ setting, type 'flutter config'. If you opt out of analytics, an opt-out    ║
         ║ event will be sent, and then no further information will be sent by the    ║
         ║ Flutter tool.                                                              ║
         ║                                                                            ║
         ║ By downloading the Flutter SDK, you agree to the Google Terms of Service.  ║
         ║ Note: The Google Privacy Policy describes how data is handled in this      ║
         ║ service.                                                                   ║
         ║                                                                            ║
         ║ Moreover, Flutter includes the Dart SDK, which may send usage metrics and  ║
         ║ crash reports to Google.                                                   ║
         ║                                                                            ║
         ║ Read about data we send with crash reports:                                ║
         ║ https://flutter.dev/docs/reference/crash-reporting                         ║
         ║                                                                            ║
         ║ See Google's privacy policy:                                               ║
         ║ https://policies.google.com/privacy                                        ║
         ╚════════════════════════════════════════════════════════════════════════════╝
       
       Setting "enable-web" value to "true".
       
       You may need to restart any open editors for them to read new settings.
-----> Running flutter clean command.
       Downloading Material fonts...                                      332ms
       Downloading Gradle Wrapper...                                        8ms
       Downloading package sky_engine...                                   94ms
       Downloading flutter_patched_sdk tools...                           222ms
       Downloading flutter_patched_sdk_product tools...                   175ms
       Downloading linux-x64 tools...                                   1,048ms
       Downloading linux-x64/font-subset tools...                          52ms
-----> Getting packages from Flutter project
       Running "flutter pub get" in build_0b9254d3...                  
Because every version of flutter from sdk depends on meta 1.7.0 and uploadcare_client >=6.2.0 depends on meta ^1.8.0, flutter from sdk is incompatible with uploadcare_client >=6.2.0.
And because uploadcare_flutter >=4.2.0 depends on uploadcare_client ^6.2.0, flutter from sdk is incompatible with uploadcare_flutter >=4.2.0.
So, because geotech depends on both flutter from sdk and uploadcare_flutter ^4.2.0, version solving failed.
pub get failed (1; So, because geotech depends on both flutter from sdk and uploadcare_flutter ^4.2.0, version solving failed.)
-----> Compiling the project with flutter build web -t lib/main_dev.dart --release --quiet
       Downloading Web SDK...                                           1,868ms
       Downloading CanvasKit...                                           430ms
       Running "flutter pub get" in build_0b9254d3...                  
Because every version of flutter from sdk depends on meta 1.7.0 and uploadcare_client >=6.2.0 depends on meta ^1.8.0, flutter from sdk is incompatible with uploadcare_client >=6.2.0.
And because uploadcare_flutter >=4.2.0 depends on uploadcare_client ^6.2.0, flutter from sdk is incompatible with uploadcare_flutter >=4.2.0.
So, because geotech depends on both flutter from sdk and uploadcare_flutter ^4.2.0, version solving failed.
pub get failed (1; So, because geotech depends on both flutter from sdk and uploadcare_flutter ^4.2.0, version solving failed.)
-----> Saving Flutter SDK in Cache
-----> Cleaning up Flutter source files and the SDK
-----> Moving static files to the deploy dir
mv: cannot stat '/tmp/build_0b9254d3/build/web/*': No such file or directory
 !     Push rejected, failed to compile https://github.com/EE/heroku-buildpack-flutter-light app.
 !     Push failed```

GroupInfoEntity not exported

Hi KonstantinKai!

Thanks for this library, its making my life so much easier trying to integrate my Flutter app with Uploadcare, really nice work!

I've noticed that GroupInfoEntity is not exported in the main package. This is entities/entities.dart, you can see that group.dart is missing.

export 'file_info.dart';
export 'list.dart';
export 'progress.dart';
export 'url.dart';
export 'video_encoding.dart';
export 'common.dart';
export 'faces.dart';

Could you add it and update to pub please?

Cheers,

Rich

Null Safety Update, Library Splitting

Hey Konstantin, are there any plans to migrate this package to null safety?

Package has been really useful and it would be nice to maintain / update it.

Thanks,

Rich

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.