EnjoyLife

이미지를 내부 저장소에 저장하는 함수 본문

안드로이드 개발/개발팁

이미지를 내부 저장소에 저장하는 함수

Aiden96 2024. 5. 1. 15:48
fun downloadImage(url: String, folderName: String, fileName: String?) {
    val appContext =  applicationContext() //본인코드에 맞게 가져온다.

    // 폴더 생성
    val folder = File(appContext.filesDir, folderName)
    if (!folder.exists() && !folder.mkdirs()) {
        Log.e("FileRepository", "Failed to create directory: $folderName")
        return
    }

    // 파일 경로 설정
    val outputFile = File(folder, fileName)

    if (outputFile.exists()) {
        Log.e("FileRepository", "File already exists: ${outputFile.path}")
        return
    }

    try {
        val inputStream = URL(url).openStream()
        val outputStream = FileOutputStream(outputFile)

        inputStream.use { input ->
            outputStream.use { output ->
                input.copyTo(output)
            }
        }

        Log.e("FileRepository", "Image downloaded successfully: ${outputFile.path}")
    } catch (e: Exception) {
        Log.e("FileRepository", "Failed to download image: ${e.message}")
    }
}