springmvc文件下载之文件名下划线问题终极解决方案

直接上代码:Action中代码片段。

@RequestMapping("download")
public String download(ModelMap model, @ModelAttribute("e") Template t, HttpServletResponse response, HttpServletRequest request) throws Exception {
Account acc = getLoginAccount();   
if(acc==null || StringUtils.isBlank(acc.getAccount())){
return ("/account/login");
}
String fileUrl = template.getFileUrl();   //url 路径, 如 http://×××××/×××/××××/image/20170525/中文.jpg
String filename = fileUrl.substring(fileUrl.lastIndexOf("/")+1);  //截取最后的文件名  -> 中文.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));
}....


重要的 processFileName方法。
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, "UTF8");
codedfilename = name;
} else if (null != agent && -1 != agent.indexOf("Mozilla")) {// 火狐,chrome等
codedfilename = new String(fileNames.getBytes("UTF-8"), "iso-8859-1");
}
} catch (Exception e) {
e.printStackTrace();
}
return codedfilename;
}

//httpConverBytes 方法
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();
for(int i=0;i<path.length();i++){
char a=path.charAt(i);   //url路径的中文部分重新编码 很重要
if(a>127){//将中文UTF-8编码
sb.append(URLEncoder.encode(String.valueOf(a), "utf-8"));
}else{
sb.append(String.valueOf(a));
}
}
URL url = new URL(sb.toString()); //创建URL
URLConnection urlconn = url.openConnection(); // 试图连接并取得返回状态码urlconn.connect();
HttpURLConnection httpconn = (HttpURLConnection) urlconn;
httpResult = httpconn.getResponseCode();
in = new BufferedInputStream(httpconn.getInputStream());

if (httpResult != HttpURLConnection.HTTP_OK){ //不等于HTTP_OK说明连接不成功
System.out.print("连接失败!");
}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;
}


通过以上处理下划线问题解决了。

 

 
posted @ 2017-05-26 09:48  西凤楼  阅读(2964)  评论(1编辑  收藏  举报
如果,您认为阅读这篇博客让您有些收获, 如果,您希望更容易地发现我的新博客,不妨关注一下。因为,我的写作热情也离不开您的肯定支持。 感谢您的阅读,如果您对我的博客所讲述的内容有兴趣,请继续关注我的后续博客。 因为有小孩,兼职卖书,路过的朋友有需要低价购买图书、点读笔、纸尿裤等资源的,可扫最上方二维码,质量有保证,价格很美丽,欢迎咨询!