使用Java Google Drive API上传文件的步骤如下:
<dependency>
<groupId>com.google.api-client</groupId>
<artifactId>google-api-client</artifactId>
<version>1.31.0</version>
</dependency>
<dependency>
<groupId>com.google.oauth-client</groupId>
<artifactId>google-oauth-client-jetty</artifactId>
<version>1.31.0</version>
</dependency>
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-drive</artifactId>
<version>v3-rev305-1.25.0</version>
</dependency>
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(HTTP_TRANSPORT)
.setJsonFactory(JSON_FACTORY)
.setClientSecrets(CLIENT_ID, CLIENT_SECRET)
.build();
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, credential, SCOPES)
.setDataStoreFactory(DATA_STORE_FACTORY)
.setAccessType("offline")
.build();
String authorizationUrl = flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI).build();
GoogleTokenResponse tokenResponse = flow.newTokenRequest(authorizationCode)
.setRedirectUri(REDIRECT_URI)
.execute();
credential = flow.createAndStoreCredential(tokenResponse, null);
Drive drive = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
.setApplicationName(APPLICATION_NAME)
.build();
File fileMetadata = new File();
fileMetadata.setName("MyFile");
java.io.File filePath = new java.io.File("path/to/file");
FileContent mediaContent = new FileContent("image/jpeg", filePath);
File file = drive.files().create(fileMetadata, mediaContent)
.setFields("id")
.execute();
System.out.println("File ID: " + file.getId());
在上面的示例中,你需要将"path/to/file"替换为你要上传的文件的路径。上传成功后,你将获得一个文件ID。
以上是使用Java Google Drive API上传文件的基本步骤。你可以根据自己的需求进行进一步的定制和扩展。如果你想了解更多关于Google Drive API的信息,可以参考腾讯云对象存储COS产品,它提供了类似的功能和服务。详情请访问:腾讯云对象存储COS。
领取专属 10元无门槛券
手把手带您无忧上云