Home > Software engineering >  Uploading PDF file to Google Drive folder and overwriting existing file
Uploading PDF file to Google Drive folder and overwriting existing file

Time:11-10

I am developing an app that uploads PDF files to a specific Google Drive folder. The file name includes the current date. The following code is for my DriveServiceHelper.class that is used to create a folder in Google Drive and then upload the PDF files into that folder using its folderID:

public class DriveServiceHelper {

Calendar c = Calendar.getInstance();
Date d = c.getTime();
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy");
String currentDate = df.format(d);
String ps_FolderKey;

private final Executor mExecutor = Executors.newSingleThreadExecutor();
private Drive mDriveService;

public DriveServiceHelper(Drive mDriveService) {
    this.mDriveService = mDriveService;
}

public Task<String> createFolder() {
    return Tasks.call(mExecutor, () -> {
        File folderMetadata = new File();
        folderMetadata.setName("Covid Assessment Sheets");
        folderMetadata.setMimeType("application/vnd.google-apps.folder");

        File myFolder = null;
        try {
            myFolder = mDriveService.files().create(folderMetadata)
                    .setFields("id")
                    .execute();
            System.out.println("Folder ID: "   myFolder.getId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (myFolder == null) {
            throw new IOException("Null result when requesting file creation");
        }
        ps_FolderKey = myFolder.getId();
        return ps_FolderKey;
    });
}

public Task<String> createFilePDF(String filePath, String folderId) {
    return Tasks.call(mExecutor, () -> {
        File fileMetaData = new File();
        fileMetaData.setName("Covid Assessment @ "   currentDate);
        fileMetaData.setParents(Collections.singletonList(folderId));
        java.io.File file = new java.io.File(filePath);
        FileContent mediaContent = new FileContent("application/pdf", file);

        File myFile = null;
        try {
            myFile = mDriveService.files().create(fileMetaData, mediaContent).execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (myFile == null) {
            throw new IOException("Null result when requesting file creation");
        }
        return myFile.getId();
    });
}
}

When uploading the same PDF to a Google Drive folder, I want to overwrite files with the same name, but instead duplicate files are created in the folder as the fileID assigned is different even if file name is the same.

Please help me understand how I should go about this, to automatically overwrite/replace files that already exist with the same name (each file is differentiated by date), and a new PDF file is created if the PDF file does not exist in the folder.

I understand that I might be using the deprecated Drive API, but I was unable to find other solutions online to help me implement what I need. I also came across solutions that include queries to search for existing Google Drive files, but I am not sure I understand how to use it to make it work for me.

Thank you

CodePudding user response:

Google Drive supports multiple files with the same name

Thus, by creating a file with an already existing name, you will not automatically overwrite the old file.

Instead you should do the following:

  • Use the method Files:list with the query name = 'Covid Assessment Sheets' to find the already existing file(s) with the same name
  • If desired, you can narrow down the results by also specifying the mimeType and the parent folder (parents)
  • Retrieve the id of the list result(s)
  • Use the method Files:delete to delete the existing file
  • Proceed to create a new file as you are already doing

In Java this would look as following:

FileList result = DriveService.files().list()
                .setQ("name = 'Covid Assessment Sheets'");
                .setFields("files(id)")
                .execute();
List<File> files = result.getFiles();
    for (File file : files) {
        DriveService.files().delete(file.getId()).execute();
    }
 

An alternative approach would be to update the contents of the already existing file instead of creating a new one.

  • Related