浏览器文件下载读取本地文件

/**
* 文件下载
* @param fileName
* @param filePath
* @param request
* @param response
* @return
*/
@RequestMapping("/download")
public String download( String fileName ,String filePath, HttpServletRequest request, HttpServletResponse response){

response.setContentType("text/html;charset=utf-8");
try {
request.setCharacterEncoding("UTF-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

java.io.BufferedInputStream bis = null;
java.io.BufferedOutputStream bos = null;
String downLoadPath = filePath; //注意不同系统的分隔符
System.out.println(downLoadPath);

try {
long fileLength = new File(downLoadPath).length();
response.reset();
response.setContentType("application/x-msdownload;");
String userAgent = request.getHeader("user-agent").toLowerCase();
//处理是否是ie浏览器
if (userAgent.contains("msie") || userAgent.contains("like gecko") ){
response.setHeader("Content-disposition", "attachment; filename=" + new String(URLEncoder.encode(fileName, "UTF-8")));
}else {
response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("utf-8"), "iso-8859-1"));
}
response.setHeader("Content-Length", String.valueOf(fileLength));

bis = new BufferedInputStream(new FileInputStream(downLoadPath));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[1024];
// 将数据写入输出流
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null)
try {
bis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (bos != null)
try {
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
上一篇:File工具类


下一篇:客户解决方案