handling filename* parameters with spaces via RFC 5987 results in '+' in filenames

痞子三分冷 提交于 2019-12-03 14:25:14
Peter Friend

So as Julian pointed out in the comments, I made a rookie Java error and forgot to do my character to byte conversion (thus I encoded the character's codepoint instead of the character's byte representation), hence the encoding was completely incorrect. This is clearly mentioned as a requirement in RFC 5987. I will be posting corrected code for doing the conversion. Once the encoding is correct, the filename* parameter is recognized properly by the browser and the filename used for the download is correct.

Below is the corrected escaping code which operates on the UTF-8 bytes of the string. The filename that was giving me trouble, now properly encoded looks like this:

Content-Disposition:attachment; filename*=UTF-8''Museum%20%E5%8D%9A%E7%89%A9%E9%A6%86.jpg

public static String rfc5987_encode(final String s) throws UnsupportedEncodingException {
    final byte[] s_bytes = s.getBytes("UTF-8");
    final int len = s_bytes.length;
    final StringBuilder sb = new StringBuilder(len << 1);
    final char[] digits = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
    final byte[] attr_char = {'!','#','$','&','+','-','.','0','1','2','3','4','5','6','7','8','9',           'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','^','_','`',                        'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','|', '~'};
    for (int i = 0; i < len; ++i) {
        final byte b = s_bytes[i];
        if (Arrays.binarySearch(attr_char, b) >= 0)
            sb.append((char) b);
        else {
            sb.append('%');
            sb.append(digits[0x0f & (b >>> 4)]);
            sb.append(digits[b & 0x0f]);
        }
    }

    return sb.toString();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!