Home > Back-end >  Java download file, the browser and apple browser Chinese garbled problem solving, effective measure
Java download file, the browser and apple browser Chinese garbled problem solving, effective measure

Time:01-05

Public HttpServletResponse download (it request, HttpServletResponse response) {
Try {
//get attachment name
The String fileName=request. The getParameter (" fileName ");//file name
//access path
String path=FILE_URL + DOMESTIC_SMS_SEND_TEMPLATE_URL;
URL the URL=new URL (path + URLEncoder encode (fileName, "utf-8"));
HttpURLConnection httpConn=(HttpURLConnection) url. OpenConnection ();
HttpConn. SetDoOutput (true);//use the URL connection for output
HttpConn. SetDoInput (true);//use URL link to enter
HttpConn. SetUseCaches (false);//ignore the cache
HttpConn. SetRequestMethod (" GET ");//set the URL request method
//can be set up request header
HttpConn. SetRequestProperty (" the content-type ", "application/octet - stream");
HttpConn. SetRequestProperty (" Connection ", "Keep Alive -");//maintain a long connection
HttpConn. SetRequestProperty (" Charset ", "utf-8");

//can be set up request header
Byte [] b=input2byte (httpConn. GetInputStream ());
The response. The reset ();
//set the response Header
String userAgent=request. GetHeader (" the user-agent "). ToLowerCase ();
//chrome head also contains safari, need to rule out the chrome
If (userAgent. The contains (" safari ") & amp; & ! UserAgent. The contains (" chrome ")) {
//handle safari garbled question
Byte [] bytesName=fileName. GetBytes (" utf-8 ");
FileName=new String (bytesName, "ISO - 8859-1");
The response. SetHeader (" the Content - Disposition, "
"The attachment; Filename="+ new String (filename. GetBytes (" utf-8"), "ISO - 8859-1"));
} else {
The response. SetHeader (" the content - the disposition ", "legislation; FileName="+ URLEncoder. Encode (fileName," utf-8 "));
}
//response. AddHeader (" the Content - the Disposition ", "legislation; Filename="+ URLEncoder. Encode (filename," utf-8 "));
//response. AddHeader (" the Content - Length ", "" + file. The Length ());
OutputStream toClient=new BufferedOutputStream (response. GetOutputStream ());
The response. SetContentType (" application/octet stream - ");
ToClient. Write (b);
ToClient. Flush ();
ToClient. Close ();
{} the catch (IOException ex)
ex.printStackTrace();
} the finally {
Logger. The info (" -- -- -- -- -- - download a template to complete - ");
}
return null;
  • Related