Snow Snow - 4 months ago 9
HTML Question

URL encode/decode on file name replace spaces with +, need alternative.

My product is a web application.

I have files that I upload and download later on, to/from my server.

I am using java.net.URLDecoder.decode() when uploading files with unicode characters and java.net.URLDecoder.encode() when downloading files in order to save the file name and finally return it to the client as expected with no question marks and stuff (?????) .


The problem is that if the file name consists spaces then the encode/decode replace them with + character which is perfectly normal because that's their business implementation, but clearly as you can understand it does not fit to my purpose.

The question is what alternative do I have to overcome this situation?

Is there build-in method for that or 3rd party package?

Answer

I found the cure!
I was just needed to use java.net.URI for that:

public static String encode(String urlString) throws UnsupportedEncodingException
{
    try
    {
        URI uri = new URI(urlString);
        return uri.toASCIIString();
    }
    catch (URISyntaxException e)
    {
        e.printStackTrace();
    }
}

The toASCIIString() escapes the special characters so when the string arrives to the browser it is shown correctly.

Comments