How to overwrite files in google drive using API flutter

213

The code you are using does a files.create file create will create a new file every time it is run.

final result = await driveApi.files.create(driveFile, uploadMedia: media,);

If you want to update an existing file then you will need to do Files.update

Share:
213
Nishuthan S
Author by

Nishuthan S

I'm a student.

Updated on December 30, 2022

Comments

  • Nishuthan S
    Nishuthan S about 1 year

    The Problem

    I'm using Google Drive to store application-specific data. I can read and write data to my drive buy whenever I want to update the config in the drive a new file is created instead of updating the old one.

    I have tried the following:

    1. Gave the file an ID but the following error appears

    Unhandled Exception: DetailedApiRequestError(status: 400, message: The provided file ID is not usable.)

    1. Got the ID generated by the API and used the same code and got the following error

    Unhandled Exception: DetailedApiRequestError(status: 409, message: A file already exists with the provided ID.)

    My Code:

        final signIn.GoogleSignInAccount account = await _googleSignIn.signIn();
        final authHeaders = await account.authHeaders;
        final authenticateClient = GoogleAuthClient(authHeaders);
        final driveApi = drive.DriveApi(authenticateClient);
    
        File _data = await _report.backupData(); //gets data to be overwriten
        final Stream<List<int>> mediaStream = _data.openRead();
        var media = new drive.Media(mediaStream, _data.lengthSync());
        var driveFile = new drive.File();
        driveFile.parents=['appDataFolder'];
        driveFile.name = "backup.mw";
        final result = await driveApi.files.create(driveFile, uploadMedia: media,);
        print("Upload result: ${result.id}");
    
  • Nishuthan S
    Nishuthan S almost 3 years
    @DalmTo will it automatically create the file if it doesn't exist?
  • DaImTo
    DaImTo almost 3 years
    file.create will create a file if it does exist. file.update requires that you send the file id of the file you are trying to update. You would need to create your own if does not exist method by first doing a file.list and searching for the file in question if it exists update it if it does create it.