如何在jsp与action上实现根据的文件地址,通过点击下载按钮 实现将文件下载下来的功能
时间: 2023-04-02 11:04:05 浏览: 61
您可以在jsp页面上添加一个下载按钮,然后在对应的action中编写下载文件的代码。具体实现步骤如下:
1. 在jsp页面上添加一个下载按钮,例如:
<button onclick="location.href='download.action?filePath=/path/to/file'">下载文件</button>
其中,download.action是对应的action名称,filePath是文件的路径。
2. 在对应的action中编写下载文件的代码,例如:
public String download() throws Exception {
String filePath = ServletActionContext.getRequest().getParameter("filePath");
File file = new File(filePath);
InputStream inputStream = new FileInputStream(file);
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
OutputStream outputStream = response.getOutputStream();
byte[] buffer = new byte[1024];
int len = ;
while ((len = inputStream.read(buffer)) > ) {
outputStream.write(buffer, , len);
}
inputStream.close();
outputStream.close();
return null;
}
其中,通过getParameter方法获取到filePath参数,然后根据文件路径创建一个File对象,再通过FileInputStream读取文件内容,设置响应的ContentType和Content-Disposition头信息,最后将文件内容写入响应的OutputStream中,完成文件下载的功能。
希望能够帮到您!
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)