Believe that a lot of people in the download file program will encounter a lot of garbled problems, their own also collated a bit, hope can help everyone.
First of all to know that each browser encoding format is not the same, the following is the main browser encoding format:
The corresponding encoding formats supported by each browser are:
1. IE browser, using Urlencoder encoding
2. Opera browser, using filename* mode
3. Safari with ISO-encoded Chinese output
4. Chrome browser with BASE64 encoding or ISO-encoded Chinese output
5. Firefox browser with Base64 or filename* or ISO-encoded Chinese output
Which encountered a lot of problems, when the background to get the file name of the foreground call Request.getparameter ("filename") has a pit, get the file name encoding format for the ISO-8859-1 format encoding, the background does not know, how to solve it? Use the construction of string to change the encoding format to Utf-8
The code is as follows
string filename = new string (Request.getparameter ("filename"). GetBytes ("Iso-8859-1"), "UTF-8");
System.out.println (filename);
String type = This.getservletcontext (). GetMimeType (filename);
//Set up in the head
Response.setheader ("Content-type", Type);
//Gets the encoding format of the file in the Stream Object server that is the working space
InputStream is = This.getservletcontext (). getResourceAsStream ("/download/" +filename);
//Determine the user's browser to modify the encoding format must be modified before the header information, otherwise garbled
String Agent = Request.getheader ("user-agent");
if (agent.contains ("Goole")) {//Only two encoding formats are used here
//BASE64 encoding Format
filename = base64encodefilename (filename);
}else{
filename = urlencoder.encode (filename, "UTF-8");
}
//Set each file to be opened for download
Response.setheader ("Content-disposition", "attrchment;filename=" +filename);
//Create write stream
outputstream OS = Response.getoutputstream ();
int len = 0;
byte[] by = new byte[1024];
While ((len= is.read ())! =-1) {
Os.write (By,0,len);
}
//mathematic only need to close one stream and the OS flow will automatically close after the Response object response is complete
is.close ();
}
Public static String Base64encodefilename (String fileName) {
Base64encoder base64encoder = new Base64encoder ();
try {
return "=? UTF-8? B? "
+ new String (Base64encoder.encode (FileName
. GetBytes ("UTF-8"))) + "?=";
} catch (Unsupportedencodingexception e) {
e.printstacktrace ();
throw new RuntimeException (e);
}
}
Java in the Chinese file name download garbled solution