首页 > 解决方案 > 应用 google drive api quickstart 时无法创建目录 /tokens

问题描述

我尝试使用https://developers.google.com/drive/api/v3/quickstart/java上指示的驱动器 API 将图像上传到谷歌驱动器。

public static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
public static final String TOKENS_DIRECTORY_PATH = "E:/tokens";

public static final List<String> SCOPES = Collections.singletonList(DriveScopes.DRIVE_APPDATA);
public static final String CREDENTIALS_FILE_PATH = "credentials.json";
public static Credential getCredentials(Context context, final NetHttpTransport HTTP_TRANSPORT) throws IOException {
    InputStream in = context.getAssets().open(CREDENTIALS_FILE_PATH);
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
            .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
            .setAccessType("offline")
            .build();
    return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
}

在这里我调用 getCredentials 方法。

private void uploadImageToDrive(Uri uri) throws IOException, GeneralSecurityException{
    try {
        GoogleDriveUpload gdu = new GoogleDriveUpload();
        final NetHttpTransport HTTP_TRANSPORT = new com.google.api.client.http.javanet.NetHttpTransport();
        Drive driveService = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, gdu.getCredentials(AccountInformationSignUpActivity.this, HTTP_TRANSPORT))
                .setApplicationName(APPLICATION_NAME)
                .build();
        String folderId = "1B7EWlFJUGmQ8qHHgMFIzuGL0i-eXl3J_";
        File fileMetadata = new File();
        fileMetadata.setName("photo.jpg");
        fileMetadata.setParents(Collections.singletonList(folderId));
        java.io.File filePath = new java.io.File(uri.getPath());
        FileContent mediaContent = new FileContent("image/jpeg", filePath);
        File file = driveService.files().create(fileMetadata, mediaContent)
                .setFields("id, parents")
                .execute();
        Log.d("File ID: ", file.getId());
    } catch (FileNotFoundException e) {
        e.getStackTrace();
    }
}

我将文件 credentials.json 放在 main/assets/credentials.json 下,它返回一个错误,说无法创建目录 /tokens。有没有我错的地方?

标签: javaandroidfiletoken

解决方案


推荐阅读