uploadScreenshot method

Future<AttachmentModel?> uploadScreenshot({
  1. required String tenantId,
  2. required File image,
  3. required BuildContext context,
})

Implementation

Future<AttachmentModel?> uploadScreenshot({
  required String tenantId,
  required File image,
  required BuildContext context,
}) async {
  var uuid = Uuid();
  String fileId = uuid.v4();
  List<String> parts = image.path.split(".");
  String fileExtension = parts[parts.length - 1];
  String fileName = "$fileId.$fileExtension";

  AttachmentModel? attachmentModel;

  try {
    AttachmentCredentialsModel? attachCreds = await getSecureStorageToken(
      tenantId: tenantId,
      storageId: "screenTraceImage",
      fileName: fileName,
    );
    if (attachCreds.uploadCredentials!.fields!.key != null) {
      var fileBytes = image.readAsBytesSync();

      var formData = attachCreds.uploadCredentials!.fields!.toJson();
      // formData['file'] = fileBytes.toString();

      var request = http.MultipartRequest(
        'POST',
        Uri.parse(constants.fileUploadUrl),
      );

      formData.forEach((key, value) {
        request.fields[key] = value;
      });

      var multipartFile = http.MultipartFile.fromBytes(
        'file',
        fileBytes,
        filename: fileName,
        contentType: httpParser.MediaType('application', 'octet-stream'),
      );
      request.files.add(multipartFile);

      var response = await request.send();

      // var response = await http.post(
      //   Uri.parse(fileUploadUrl),
      //   headers: {
      //     'Content-Type': 'application/x-www-form-urlencoded',
      //   },
      //   body: formData,
      // );
      print("FILE UPLOAD RESPONSE : " + response.statusCode.toString());
      print("FILE UPLOADED AT: " + attachCreds.downloadUrl.toString());

      attachmentModel = AttachmentModel(
        downloadUrl: attachCreds.downloadUrl,
        id: fileId,
        name: fileName,
        isNew: true,
        privateUrl: attachCreds.privateUrl,
        publicUrl: attachCreds.uploadCredentials!.publicUrl,
        sizeInBytes: fileBytes.length,
        // createdAt: DateTime.now().toIso8601String(),
        // updatedAt: DateTime.now().toIso8601String(),
      );
      return attachmentModel;
    }
  } catch (e) {
    print("ERROR uploadAvatar: $e");
  }
}