实现文件下载,备注已经做好,这里就不详细说明了
public void downloadLocal(HttpServletResponse response)
throws UnsupportedEncodingException, FileNotFoundException {
String fileName = "红太狼.txt".toString(); // 文件的默认保存名
//更改文件名编码
String gFileName = URLEncoder.encode(fileName, "UTF-8");
// 读到流中
//要下载文件的存放路径
InputStream inStream = new FileInputStream("E:/aa.txt");
// 设置输出的格式
//去除前后空格
response.reset();
//激活浏览器弹出窗口
response.setContentType("application/x-msdownload");
//浏览器弹出窗口显示的文件名
response.addHeader("Content-Disposition", "attachment; filename="+gFileName);
// 循环取出流中的数据
byte[] b = new byte[1024];
int len;
try {
while ((len = inStream.read(b)) > 0)
response.getOutputStream().write(b, 0, len);
inStream.close();//关闭流
} catch (IOException e) {
e.printStackTrace();
}
}
发现一个小问题就是,如进行下载名为:文件(3).txt,下载时显示名为:文件+(3).txt
解决办法是:把+进行替换
也就是:String gFileName = URLEncoder.encode(fileName, "UTF-8");
String dFileName = gFileName.replaceAll("\\+", "%20");
获取要下载的文件大小
FileChannel fc= ((FileInputStream) inStream).getChannel(); //文件大小
logger.info("文件大小为:"+fc.size()+"k");