How do I upload image file to google drive from android

1.2k Views Asked by At

I'm having a issue uploading a file to Google Drive.

W/System.err: java.io.FileNotFoundException: /storage/emulated/0/Android/data/dev/files/backup/https:/i.picsum.photos/id/723/200/200.jpg? (No such file or directory)

This is my following code.

Source code from https://www.section.io/engineering-education/backup-services-with-google-drive-api-in-android/

class GoogleDriveUtils(private val context: Context) {

fun initializeGoogleClient() {
    val signInOptions = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
        .requestEmail()
        .requestScopes(Scope(DriveScopes.DRIVE_FILE), Scope(DriveScopes.DRIVE_APPDATA))
        .build()
    val client = GoogleSignIn.getClient(context, signInOptions)

    (context as? Activity)?.startActivityForResult(
        client.signInIntent,
        SignUpFragment.RC_SIGN_IN
    )

}

fun googleDriverIntegrate() {
    GoogleSignIn.getLastSignedInAccount(context)?.let { googleAccount ->

        val credential = GoogleAccountCredential.usingOAuth2(
            context, listOf(DriveScopes.DRIVE_FILE)
        )
        credential.selectedAccount = googleAccount.account!!
    }

}


fun getDriveService(): Drive? {
    GoogleSignIn.getLastSignedInAccount(context)?.let { googleAccount ->
        val credential = GoogleAccountCredential.usingOAuth2(
            context, listOf(DriveScopes.DRIVE_FILE)
        )
        credential.selectedAccount = googleAccount.account!!
        return Drive.Builder(
            AndroidHttp.newCompatibleTransport(),
            JacksonFactory.getDefaultInstance(),
            credential
        )
            .setApplicationName(context.getString(R.string.app_name))
            .build()
    }
    return null
}


fun accessDriveFiles(savePath: String?) {
    getDriveService()?.let { googleDriveService ->
        CoroutineScope(Dispatchers.IO).launch {
            var pageToken: String?

            do {
                val result = googleDriveService.files().list().apply {
                    spaces = "drive"
                    fields = "nextPageToken, files(id, name)"
                    pageToken = this.pageToken
                }.execute()

                result.files.forEach { file ->
                    Log.d("FILE", ("name=${file.name} id=${file.id}"))
                }
            } while (pageToken != null)
        }

        val FILE_NAME_BACKUP="test.txt"
        val localFileDirectory = File(context.getExternalFilesDir("backup")!!.toURI())
        val actualFile = savePath?.let { File(it) }

        val gFile = com.google.api.services.drive.model.File()
        if (actualFile != null) {
            gFile.name = actualFile.name
        }
        if (actualFile != null) {
            Log.e("actualFile", actualFile.name)
        }
        val fileContent = FileContent("text/plain", actualFile)
        googleDriveService.Files().create(gFile, fileContent).execute()
    }
}

fun uploadFileToGDrive(path: String?) {
    getDriveService()?.let { googleDriveService ->
        CoroutineScope(Dispatchers.IO).launch {
            try {

                val localFileDirectory =
                    File(context.getExternalFilesDir("backup")!!.toURI())

                val actualFile = File("${localFileDirectory}/$path")
                val gFile = com.google.api.services.drive.model.File()
                gFile.name = actualFile.name
                val fileContent = FileContent("image/jpeg", actualFile)
                googleDriveService.Files().create(gFile, fileContent).execute()

                Log.e("File uploaded", "File uploaded")
               

            } catch (exception: Exception) {
                exception.printStackTrace()
            }
        }
    } ?: Toast.makeText(context, "Please Log In first!", LENGTH_SHORT).show()
}

fun downloadFileFromGDrive(id: String) {
    getDriveService()?.let { googleDriveService ->
        CoroutineScope(Dispatchers.IO).launch {
            googleDriveService.Files().get(id).execute()
        }
    } ?: Toast.makeText(context, "Please Log In first!", LENGTH_SHORT).show()
}

}

0

There are 0 best solutions below