pushFile method

Future<File> pushFile(
  1. File file,
  2. String path, {
  3. String? mimeType,
})

Copies a file from the users' device to Google Drive. Path must be supplied like path/to/file.txt. Last entry after the final forward-slash must not end with a forward slash, and will be treated as the file name.

Implementation

Future<drive.File> pushFile(final File file, final String path, {final String? mimeType}) async {
  String? containingFolderId;
  if (path.contains('/')) {
    final containingFolders = path.substring(0, path.lastIndexOf('/'));
    final foldersId = await createFoldersRecursively(containingFolders);
    containingFolderId = foldersId.last.id;
  }
  final fileName = path.contains('/') ? path.split('/').last : path;

  final existingFileQuery = QueryBuilder.fileQuery(
    fileName,
    mimeType: lookupMimeType(path),
  );

  final existingFileData = await files.list(
    q: existingFileQuery,
    $fields: 'files(kind,id,name,mimeType,md5Checksum)',
  );

  if (existingFileData.files!.isNotEmpty) {
    final remoteMd5 = existingFileData.files?.first.md5Checksum;
    final localMd5 = await getMD5(file.path);
    if (remoteMd5 == localMd5) {
      print('Remote file is the same, not pushing file.');
      return existingFileData.files!.first;
    }
  }
  final driveFile =
      drive.File(name: fileName, mimeType: mimeType ?? lookupMimeType(fileName), parents: containingFolderId == null ? [] : [containingFolderId]);

  final length = await file.length();
  final fileContents = file.openRead();

  final destinationFile = await drive.DriveApi(GoogleAuthClient()).files.create(
        driveFile,
        uploadMedia: drive.Media(
          fileContents,
          length,
        ),
      );
  return destinationFile;
}