文件下载,可解决下载时各种异常及乱码,空格变+号(2)


fis = new BufferedInputStream(new FileInputStream(path));
byte[] buffer = new byte[fis.available()];
//byte[] buffer = new byte[1024];
fis.read(buffer);
fis.close();

response.reset();
System.out.println("downloadName---->" + fileName);
fileName = encodeFileName(request,fileName);
//解决下载时,空格变加号
fileName = StringUtils.replace(fileName, "+", "%20");
response
.addHeader("Content-Disposition", "attachment;filename="
+ fileName);
response.addHeader("Content-Length", "" + file.length()); // 设置返回的文件类型
toClient = new BufferedOutputStream(response
.getOutputStream()); // 得到向客户端输出二进制数据的对象
toClient.write(buffer); // 输出数据
toClient.flush();
toClient.close();
return fileName;
} catch (IOException e) {
System.out.println("----------下载文件时,输出流发生异常--------------");
try {
if(null != fis)
{
fis.close();
}
if(null != toClient)
{
toClient.close();
}

} catch (IOException e1) {
e1.printStackTrace();
}

return fileName;
}catch(Exception e){
System.out.println("----------下载文件时发生异常--------------");
return null;
}
}


public static String encodeFileName(HttpServletRequest request,
String fileName) throws UnsupportedEncodingException {
String agent = request.getHeader("USER-AGENT");
if (null != agent && -1 != agent.indexOf("MSIE")) {
System.out.println("------IE浏览器下载");
return URLEncoder.encode(fileName, "UTF8");
} /*else if (null != agent && -1 != agent.indexOf("Mozilla")) {
System.out.println("------火狐浏览器下载");
return "=?UTF-8?B?"
+ (new String(Base64.encodeBase64(fileName
.getBytes("UTF-8")))) + "?=";
}*/ else {
System.out.println("------其它浏览器下载");
//return fileName;
return new String(fileName.getBytes(),"iso-8859-1");
}

}
展开阅读全文

没有更多推荐了,返回首页