【问题标题】:How to downlaod file from google drive and display in image in android如何从谷歌驱动器下载文件并在android中显示在图像中
【发布时间】:2022-08-18 17:35:33
【问题描述】:

这是我的以下代码。

我在显示来自 Google 云端硬盘的图片时遇到问题。

源代码来自https://www.section.io/engineering-education/backup-services-with-google-drive-api-in-android/

我也使用过这个图像 url https://drive.google.com/uc?id=FILE_ID,但只适用于链接访问不受限制的图像的任何人。

fun downloadFileFromGDrive(id: String) {
    getDriveService()?.let { googleDriveService ->
        CoroutineScope(Dispatchers.IO).launch {

            val gDriveFile = googleDriveService.Files().get(id).execute()
            Log.e(\"gDriveFile\", gDriveFile.toString())

           val outputStream: OutputStream = ByteArrayOutputStream()
            googleDriveService.files()[id].executeMediaAndDownloadTo(outputStream)

        }
    } ?: Toast.makeText(context, \"Please Log In first!\", LENGTH_SHORT).show()
}
  • 你忘了提这个问题。如果您关注最新的SDK docs,那就更好了。
  • Google 云端硬盘并非旨在提供文件托管服务。每天一个文件的下载次数限制为 250 次左右。

标签: android kotlin google-drive-api kotlin-coroutines


【解决方案1】:

使用以下功能它将下载谷歌驱动器图像并将其保存到应用程序私人文件夹中。

 fun downloadFileFromGDrive(id: String) {
        getDriveService()?.let { googleDriveService ->
            CoroutineScope(Dispatchers.IO).launch {
                Log.e("idDownload", id)
                val file = File(context.filesDir, "${id}.jpg")
                if (!file.exists()) {
                    try {
                        val gDriveFile = googleDriveService.Files().get(id).execute()
                        saveImageInFilesDir(gDriveFile.id)
                    } catch (e: Exception) {
                        println("!!! Handle Exception $e")
                    }
                }
            }
        } ?: ""
    }


private fun saveImageInFilesDir(id: String?) {
    getDriveService()?.let { googleDriveService ->
        CoroutineScope(Dispatchers.IO).launch {
            val file = File(context.filesDir, "${id}.jpg")
            try {
                val outputStream = FileOutputStream(file)
                googleDriveService.files()[id]
                    .executeMediaAndDownloadTo(outputStream)
                if (id != null) {
                    googleDriveService.readFile(id)
                }
           
                outputStream.flush()
                outputStream.close()

            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

}

【讨论】:

    猜你喜欢
    • 2016-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多