如何在jsp与action上实现根据的文件地址,通过点击下载按钮 实现将文件下载下来的功能
时间: 2023-04-04 21:00:31 浏览: 172
您可以在jsp页面上添加一个下载按钮,然后在对应的action中编写下载文件的代码。具体实现步骤如下:
1. 在jsp页面上添加一个下载按钮,例如:
<button onclick="location.href='download.action?filePath=/path/to/file'">下载文件</button>
其中,download.action是对应的action名称,filePath是文件的路径。
2. 在对应的action中编写下载文件的代码,例如:
public String download() {
String filePath = request.getParameter("filePath");
File file = new File(filePath);
if (!file.exists()) {
return ERROR;
}
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
try (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);
}
} catch (IOException e) {
e.printStackTrace();
return ERROR;
}
return NONE;
}
其中,request和response是在action中自动注入的对象,可以直接使用。该方法首先获取文件路径,然后判断文件是否存在,如果不存在则返回错误。接着设置响应的Content-Type和Content-Disposition头,告诉浏览器下载文件。最后将文件内容写入响应的输出流中,完成文件下载。
阅读全文
相关推荐

















