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

本文介绍了两种获取Tomcat路径的方法及如何通过Action实现文件下载。同时提供了在不同场景下直接调用Action的方式,包括使用Ajax、表单提交、iframe重定向及window.location.href等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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来解决。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值