Directly on the code: code fragment in action.
@RequestMapping ("Download")
@ModelAttribute (throws Exception {
Account ACC = Getloginaccount ();
if (acc==null | | StringUtils. IsBlank (Acc.getaccount ())) {
Return ("/account/login");
}
String fileUrl = Template.getfileurl (); URL path, such as http://xxxxx/xxx/xxxx/image/20170525/Chinese. jpg
String filename = fileurl.substring (Fileurl.lastindexof (1); Intercept the last filename-> Chinese. JPG
filename = processfilename (request, filename);
Bufferedoutputstream bf = null;
try {
Response.setheader (" Content-disposition ", " attachment; filename = "+ filename");
BF = new Bufferedoutputstream (Response.getoutputstream ());
Bf.write (this. Httpconverbytes (fileurl,request));
} ....
Important Processfilename method.
public static string Processfilename (HttpServletRequest request, string fileNames) {
String Codedfilename =Null
try {
String Agent = Request.getheader ("User-agent");
if (Null! = Agent &&-1! = Agent.indexof ("MSIE") | |Null! = Agent
&&-1! = Agent.indexof ("Trident")) {Ie
String name = Java.net.URLEncoder.Encode (FileNames, Codedfilename = name;
} else if (1! = Agent.indexof (" Mozilla ") {//Firefox, Chrome, etc.
Codedfilename = new String (Filenames.getbytes ( }
} catch (Exception e) {
E.printstacktrace ();
}
return codedfilename;
}
//httpconverbytes method
public static byte[] Httpconverbytes (String path,httpservletrequest request) {
Bufferedinputstream in =Null
Bytearrayoutputstream out =Null
URLConnection conn =Null
int httpresult=0;
try {
StringBuffer SB =New StringBuffer ();
Forint i=0;i<path.length (); i++) {
Char A=path.charat (i); The Chinese part of the URL path is re-encoded very important
if (a>127) {Encode the Chinese UTF-8
Sb.append (Urlencoder.Encode (String.ValueOf (a),"Utf-8"));
}else{
Sb.append (String.ValueOf (a));
}
}
URL url =New URL (Sb.tostring ());Create URL
URLConnection urlconn = Url.openconnection ();Attempt to connect and get return status code Urlconn.connect ();
HttpURLConnection httpconn = (httpurlconnection) urlconn;
Httpresult = Httpconn.getresponsecode ();
in =New Bufferedinputstream (Httpconn.getinputstream ());
if (httpresult! = httpurlconnection.HTTP_OK) {Not equal to HTTP_OK indicates that the connection was unsuccessful
System.Out.print ("Connection Failed! ");
}else {
out =New Bytearrayoutputstream (1024);
byte[] Temp =New byte[1024];
int size =0;
while (size = In.read (temp))! =-1) {
Out.write (temp, 0, size);
}
byte["content = Out.tobytearray ();
return content;
}
} catch (Exception e) {
E.printstacktrace ();
}
finally {
try {
In.close ();
} catch (IOException e) {
E.printstacktrace ();
}
try {
Out.close ();
} catch (IOException e) {
E.printstacktrace ();
}
}
return null;
} The
is resolved with the underscore issue above.
Springmvc File Download file name Dash problem the ultimate solution