您的位置:首页 > 编程语言 > Java开发

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

2017-05-26 09:48 337 查看
直接上代码:Action中代码片段。

@RequestMapping("download")
publicStringdownload(ModelMapmodel,@ModelAttribute("e")Templatet,HttpServletResponseresponse,HttpServletRequestrequest)throwsException{
Accountacc=getLoginAccount();   
if(acc==null||StringUtils.isBlank(acc.getAccount())){
return("/account/login");
}

StringfileUrl=template.getFileUrl();   //url 路径, 如 http://×××××/×××/××××/image/20170525/中文.jpg
Stringfilename=fileUrl.substring(fileUrl.lastIndexOf("/")+1);  //截取最后的文件名  -> 中文.jpg
filename=processFileName(request,filename);
BufferedOutputStreambf=null;
try{
response.setHeader("Content-disposition","attachment;filename="+filename);
bf=newBufferedOutputStream(response.getOutputStream());
bf.write(this.httpConverBytes(fileUrl,request));
}....

重要的 processFileName方法。

publicstaticStringprocessFileName(HttpServletRequestrequest,StringfileNames){
Stringcodedfilename=null;
try{
Stringagent=request.getHeader("USER-AGENT");
if(null!=agent&&-1!=agent.indexOf("MSIE")||null!=agent
&&-1!=agent.indexOf("Trident")){//ie
Stringname=java.net.URLEncoder.encode(fileNames,"UTF8");
codedfilename=name;
}elseif(null!=agent&&-1!=agent.indexOf("Mozilla")){//火狐,chrome等
codedfilename=newString(fileNames.getBytes("UTF-8"),"iso-8859-1");
}
}catch(Exceptione){
e.printStackTrace();
}
returncodedfilename;
}

//httpConverBytes 方法

publicstaticbyte[]httpConverBytes(Stringpath,HttpServletRequestrequest){
BufferedInputStreamin=null;
ByteArrayOutputStreamout=null;
URLConnectionconn=null;
inthttpResult=0;
try{
StringBuffersb=newStringBuffer();
for(inti=0;i<path.length();i++){
chara=path.charAt(i);   //url路径的中文部分重新编码 很重要
if(a>127){//将中文UTF-8编码
sb.append(URLEncoder.encode(String.valueOf(a),"utf-8"));
}else{
sb.append(String.valueOf(a));
}
}
URLurl=newURL(sb.toString());//创建URL
URLConnectionurlconn=url.openConnection();//试图连接并取得返回状态码urlconn.connect();
HttpURLConnectionhttpconn=(HttpURLConnection)urlconn;
httpResult=httpconn.getResponseCode();
in=newBufferedInputStream(httpconn.getInputStream());

if(httpResult!=HttpURLConnection.HTTP_OK){//不等于HTTP_OK说明连接不成功
System.out.print("连接失败!");
}else{
out=newByteArrayOutputStream(1024);
byte[]temp=newbyte[1024];
intsize=0;
while((size=in.read(temp))!=-1){
out.write(temp,0,size);
}
byte[]content=out.toByteArray();
returncontent;
}
}catch(Exceptione){
e.printStackTrace();
}
finally{
try{
in.close();
}catch(IOExceptione){
e.printStackTrace();
}
try{
out.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
returnnull;
}

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




                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: