如何在jsp与action上实现根据的文件地址,通过点击下载按钮 实现将文件下载下来的功能
时间: 2023-04-02 20:04:08 浏览: 64
您可以在jsp页面上设置一个下载按钮,然后在对应的action中,使用Java IO流读取文件,将文件内容写入HttpServletResponse对象中,设置响应头,使浏览器能够识别文件类型并下载。具体实现可以参考以下代码:
在jsp页面上设置下载按钮:
<button onclick="location.href='download.action?filePath=/path/to/file'">下载文件</button>
在对应的action中,使用Java IO流读取文件,将文件内容写入HttpServletResponse对象中,设置响应头,使浏览器能够识别文件类型并下载:
public class DownloadAction extends ActionSupport {
private String filePath;
public String execute() throws Exception {
HttpServletResponse response = ServletActionContext.getResponse();
File file = new File(filePath);
if (!file.exists()) {
return ERROR;
}
String fileName = file.getName();
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
InputStream in = new FileInputStream(file);
OutputStream out = response.getOutputStream();
byte[] buffer = new byte[1024];
int len = ;
while ((len = in.read(buffer)) > ) {
out.write(buffer, , len);
}
in.close();
out.close();
return NONE;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
}
其中,filePath是文件的绝对路径,可以通过jsp页面传递过来。在action中,先判断文件是否存在,如果不存在则返回ERROR,否则设置响应头,将文件内容写入HttpServletResponse对象中,最后返回NONE。