File Download-the Chinese Struts2 file is displayed as a space.
File Download-the Chinese Struts2 file is displayed as a space.
Recently, file downloading is used in the company's projects. Based on the underlying layer, the file downloading mode of struts2 is determined. Most of the garbled characters solve the problem. When a Chinese file is downloaded, Chinese characters are displayed as spaces. After nearly three hours of searching various documents and meditation, I finally found the problem. I have not published any articles about this phenomenon on the Internet, so I will write it out and share it with you.
In the Struts2 configuration file:
Text/plain
Application/octet-stream; charsets = ISO8859-1
Attachment; fileName =$ {downloadFileName}
InputStream
1024
Java usage:
PublicString getDownloadFileName (){
String fileName1 = ServletActionContext. getRequest (). getParameter (fileName );
Try {
FileName1 = new String (fileName1.getBytes (ISO8859-1), UTF-8 );
} Catch (UnsupportedEncodingException e1 ){
E1.printStackTrace ();
}
String downFileName = fileName1;
Try {
DownFileName = newString (downFileName. getBytes (), ISO8859-1 );
} Catch (Exception e ){
E. printStackTrace ();
}
System. out. println (downFileName ============================>+ downFileName );
Return downFileName;
}
PublicInputStream getInputStream () throws Exception {
String fileName1 = ServletActionContext. getRequest (). getParameter (fileName );
Stringname = new String (fileName1.getBytes (ISO8859-1), UTF-8 );
System. out. println (name ============>+ name );
InputStreamin = ServletActionContext. getServletContext (). getResourceAsStream (/custMonitorFile/+ name );
System. out. println (in );
Returnin;
}
@ Override
PublicString execute () throws Exception {
Return SUCCESS;
}
Note:
Why is the Java source code transferred twice?
Answer:
// Transcoding is required for fields obtained from jsp get or post for the first time.
String fileName1 = ServletActionContext. getRequest (). getParameter (fileName );
FileName1 = newString (fileName1.getBytes (ISO8859-1), UTF-8 );
// The second time you set the Chinese file name to be sent to the client in ISO8859-1 format.
String downFileName = fileName1;
DownFileName = newString (downFileName. getBytes (), ISO8859-1 );
Note: Make sure you understand the purpose, origin, and end of each transcoding task.