Solution to garbled file names during Java File Download

Source: Internet
Author: User

Copy codeThe Code is as follows: public static String toUtf8String (String s ){

StringBuffer sb = new StringBuffer ();
For (int I = 0; I <s. length (); I ++ ){
Char c = s. charAt (I );
If (c> = 0 & c <= 255 ){
Sb. append (c );
} Else {
Byte [] B;
Try {
B = Character. toString (c). getBytes ("UTF-8 ");
} Catch (Exception ex ){
Predictionutil. error ("an error occurred when converting Chinese characters in the file name into UTF-8 encoded strings. The input string is:" + s );
B = new byte [0];
}
For (int j = 0; j <B. length; j ++ ){
Int k = B [j];
If (k <0)
K + = 256;
Sb. append ("%" + Integer. toHexString (k). toUpperCase ());
}
}
}
Return sb. toString ();
}

/**
* Convert Chinese characters in the file name into UTF-8 encoded strings based on different browsers, so that the file name can be correctly displayed during download.
*
* @ Param s
* Original file name
* @ Return the reencoded file name
*/
Public static String toUtf8String (HttpServletRequest request, String s ){
String agent = request. getHeader ("User-Agent ");
Try {
Boolean isFireFox = (agent! = Null & agent. toLowerCase (). indexOf ("firefox ")! =-1 );
If (isFireFox ){
S = new String (s. getBytes ("UTF-8"), "ISO8859-1 ");
} Else {
S = StringUtil. toUtf8String (s );
If (agent! = Null & agent. indexOf ("MSIE ")! =-1 )){
// See http://support.microsoft.com/default.aspx? Kbid = 816868
If (s. length () & gt; 150 ){
// Obtain the possible Encoding Based on the locale of the request
S = new String (s. getBytes ("UTF-8"), "ISO8859-1 ");
}
}
}
} Catch (UnsupportedEncodingException e ){
E. printStackTrace ();
}
Return s;
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.