uploadImage method

Future<String> uploadImage(
  1. ViamImage image,
  2. String partId, {
  3. String? fileName,
  4. String? componentType,
  5. String? componentName,
  6. String? methodName,
  7. Map<String, Any>? methodParameters,
  8. Iterable<String> tags = const [],
})

Upload an image to Viam's Data Manager

If no name is provided, the current timestamp will be used as the filename.

import 'package:file_picker/file_picker.dart';
import 'package:image/image.dart' as img;

Future<ViamImage> createViamImageFromFile() async {
  try {
    // Open file picker
    FilePickerResult? result = await FilePicker.platform.pickFiles(
      type: FileType.image,
      allowMultiple: false,
    );

    if (result == null || result.files.isEmpty) {
      throw Exception('No file selected');
    }

    // For mobile, we get the file path and read it
    final String? filePath = result.files.first.path;
    if (filePath == null) {
      throw Exception('Invalid file path');
    }

    // Read the file as bytes
    final File file = File(filePath);
    final Uint8List bytes = await file.readAsBytes();

    if (bytes.isEmpty) {
      throw Exception('File is empty');
    }

    print('Successfully read file: ${bytes.length} bytes');

    // Create ViamImage with the bytes
    return ViamImage(
      bytes,
      MimeType.jpeg, // or determine MIME type from file extension
     );
  } catch (e, stackTrace) {
    print('Error creating ViamImage: $e');
    print('Stack trace: $stackTrace');
    rethrow;
  }
}
void _uploadData() async {
  try {
    _viam = await Viam.withApiKey(
      dotenv.env['API_KEY_ID'] ?? '',
      dotenv.env['API_KEY'] ?? ''
    );
    final dataClient = _viam.dataClient;

    try {
       ViamImage img = await createViamImageFromFile();

       final fileId = await dataClient.uploadImage(
         img,
         "<YOUR-PART-ID>",
         fileName: "myUploadedImage.jpeg",
         componentType: "rdk:component:camera",
         componentName: "camera-1",
         methodName: "ReadImage"
       );
       print('Successfully uploaded image with fileId: $fileId');
      } catch (e) {
        print('Error uploading image: $e');
      }
    }
 }

For more information, see Data Client API.

Implementation

Future<String> uploadImage(ViamImage image, String partId,
    {String? fileName,
    String? componentType,
    String? componentName,
    String? methodName,
    Map<String, Any>? methodParameters,
    Iterable<String> tags = const []}) async {
  final metadata = UploadMetadata()
    ..partId = partId
    ..type = DataType.DATA_TYPE_FILE
    ..fileName = fileName ?? DateTime.now().toIso8601String()
    ..fileExtension = '.${image.mimeType.type}'
    ..tags.addAll(tags);
  if (componentType != null) metadata.componentType = componentType;
  if (componentName != null) metadata.componentName = componentName;
  if (methodName != null) metadata.methodName = methodName;
  if (methodParameters != null) metadata.methodParameters.addAll(methodParameters);
  final metadataRequest = FileUploadRequest()..metadata = metadata;

  // Make requests that are at most 2MB large (max gRPC request size is 4MB)
  final dataRequests = image.raw.slices(2 * 1024 * 1024).map((e) => FileUploadRequest()..fileContents = (FileData()..data = e));

  final requestStream = Stream.fromIterable([metadataRequest, ...dataRequests]);
  final response = await _dataSyncClient.fileUpload(requestStream);
  return response.fileId;
}