Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improved File Name Extraction in getFileNameFromUrl Function #48

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

MehdiSekoba
Copy link

In the original implementation, the getFileNameFromUrl function generated a file name by combining a random UUID with the file name guessed by URLUtil.guessFileName. This approach worked, but it did not always ensure that the file name was directly extracted from the URL.

Original Code:

fun getFileNameFromUrl(url: String): String {
    val guessFileName = URLUtil.guessFileName(url, null, null)
    return UUID.randomUUID().toString() + "-" + guessFileName
}

My Changes:

I modified the function to directly extract the file name from the URL itself, specifically by using the Uri class. Here's the updated implementation:

fun getFileNameFromUrl(url: String): String? {
    return if (URLUtil.isValidUrl(url)) {
        val uri = Uri.parse(url)
        uri.lastPathSegment
    } else {
        null
    }
}

Key Improvements:

  1. Direct File Name Extraction:

    • Instead of appending a UUID, the new implementation directly retrieves the file name from the last path segment of the URL using uri.lastPathSegment.
  2. Validation:

    • The function now validates the URL using URLUtil.isValidUrl. If the URL is invalid, the function returns null instead of proceeding with incorrect data.
  3. Cleaner and More Intuitive Naming:

    • The downloaded file retains the exact name specified in the URL, which is more predictable and user-friendly.

Benefits:

  • Ensures that file names remain consistent with the URL's actual content.
  • Simplifies the logic by removing the need to append a random UUID.
  • Adds error handling for invalid URLs, preventing unexpected behavior.

photo_2024-12-29_09-24-01

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant