Last active
July 5, 2023 13:47
-
-
Save kota65535/08c6eb103b110a8f2a36f89c335678ec to your computer and use it in GitHub Desktop.
GoogleDriveUploader
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Data | |
public class DriveConfig { | |
@NotNull | |
private String credentials; | |
@NotNull | |
private String driveId; | |
@NotNull | |
private String folderId; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class GoogleDriveUploader { | |
private final DriveConfig config; | |
private final Drive drive; | |
public GoogleDriveUploader(AppConfig appConfig) throws IOException, GeneralSecurityException { | |
config = appConfig.getDrive(); | |
GoogleCredentials credentials = ServiceAccountCredentials | |
.fromStream(new ByteArrayInputStream(config.getCredentials().getBytes())) | |
.createScoped(DriveScopes.all()); | |
drive = new Drive.Builder( | |
GoogleNetHttpTransport.newTrustedTransport(), | |
new GsonFactory(), | |
new HttpCredentialsAdapter(credentials)) | |
.setApplicationName("Google Drive Sandbox") | |
.build(); | |
} | |
public List<File> list() throws IOException { | |
FileList result = drive.files().list() | |
.setCorpora("drive") | |
.setDriveId(config.getDriveId()) | |
.setQ("'%s' in parents".formatted(config.getFolderId())) | |
.setSupportsTeamDrives(true) | |
.setIncludeItemsFromAllDrives(true) | |
.execute(); | |
return result.getFiles(); | |
} | |
public void upload(String filename, String content, String charset) throws IOException { | |
File fileMeta = new File(); | |
fileMeta.setName(filename); | |
fileMeta.setParents(List.of(config.getFolderId())); | |
File f = drive.files() | |
.create(fileMeta, | |
new InputStreamContent("text/plain", new ByteArrayInputStream(content.getBytes(charset)))) | |
.setSupportsTeamDrives(true) | |
.execute(); | |
System.out.print(f.getId()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment