`
bcyy
  • 浏览: 1818197 次
文章分类
社区版块
存档分类
最新评论

j2ee中下载文件,js调用action,及获得tomcat的物理路径等知识点

 
阅读更多

1.获取tomcat的路径:

两个获得路径的方法:

System.out.println(new File(System.getProperty("catalina.home")));

System.out.println(new File(System.getProperty("user.dir")));

可根据需要使用。当然,也有直接获得项目的物理路径的:

ServletActionContext.getServletContext().getRealPath("/") + "/modules/download/batchvehicle.xlsx";


2.js直接调用action

思路:1:ajax.2表单提交3.iframe重定向4.winow.location.href=""


3.j2ee下载文件:

说也奇怪,以前全是jsp时,用window.open(url) 就直接可以了。但现在加入框架,怎么做也做不出来了。

所以写在action层了:

public void downLoadVehiclePattern(){
OutputStream ous = null;
InputStream tis= null;
try {
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("text/html;charset=utf-8");
response.reset();
String header = "attachment; filename=BatchVehicle.xlsx";
header = new String(header.getBytes(), "UTF-8");
response.setHeader("Content-disposition", header);
String excelPath = ServletActionContext.getServletContext().getRealPath("/") + "/modules/download/batchvehicle.xlsx";
File file = new File(excelPath);
ous = response.getOutputStream();
tis= new FileInputStream(file);

byte[] bufs = new byte[1024];
int len = 0;
while((len = tis.read(bufs)) != -1) {
ous.write(bufs,0,len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(ous != null) {
try {
ous.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(tis != null) {
try {
tis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}


而且在前台,由于某种原因,用href 不方便,只能用js

如果用window.open会生成一个新页面,故用window.location.href来解决。



分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics