1
我正嘗試使用谷歌服務帳戶將文件上傳到谷歌硬盤。無法將文件從服務帳戶上傳到Google雲端硬盤
司機服務
public static Drive getDriveService(String secretKeyFile) throws GeneralSecurityException,
IOException, URISyntaxException {
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setServiceAccountScopes(DriveScopes.DRIVE)
.setServiceAccountPrivateKeyFromP12File(
new java.io.File(secretKeyFile))
.build();
Drive service = new Drive.Builder(httpTransport, jsonFactory, null)
.setHttpRequestInitializer(credential).setApplicationName("appl name").build();
return service;
}
插入文件
private static File insertFile(Drive service, String title, String description,String mimeType, String filename) {
File body = new File();
body.setTitle(title);
body.setDescription(description);
body.setMimeType(mimeType);
java.io.File fileContent = new java.io.File(filename);
FileContent mediaContent = new FileContent(mimeType, fileContent);
try {
File file = service.files().insert(body, mediaContent).execute();
return file;
} catch (IOException e) {
System.out.println("An error occured: " + e);
return null;
}
}
主要方法
Drive service=null;
try {
String secretFile= "somedigit-privatekey.p12";
service = getDriveService(secretFile);
} catch (URISyntaxException ex) {
ex.printStackTrace();
}
File insertFile = insertFile(service, "test title", "File description", "text/plain", "c:\\test.txt");
List list = service.files().list();
System.out.println("Files Id : "+insertFile.getId());
System.out.println("Count Files : "+list.size());
現在,我的問題是:
- 如何以及在哪裏可以查看該文件被上傳?
- 爲什麼它返回文件ID,但list.size()爲零。
- 它也會返回下載鏈接,但是當我將該鏈接粘貼到 瀏覽器中時,它不會下載任何文件。
最好爲每個問題啓動個別主題。不過,我會在下面提供一個答案。 –
你可以這樣做?我有同樣的問題:( – victorpacheco3107
我的問題:http://stackoverflow.com/questions/26146712/upload-file-to-google-drive-in-java-without-oauth – victorpacheco3107