请求处理方法:
@RequestMapping("/download")
public String download(HttpServletRequest request, HttpServletResponse response) throws Exception {
// 获取下载文件路径
String realPath = request.getServletContext().getRealPath("/img/img.png");
// 将文件路径封装为File对象
File path = new File(realPath);
// 根据File对象获取文件名
String fileName = path.getName();
// 设置响应头:content-disposition 设置文件下载的打开方式,默认在网页上打开
// 设置attachment;filename= 设置以下载的形式打开文件
// "UTF-8" 设置编码,以防文件名称中的中文出现乱码
response.setHeader("content-disposition","attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));
InputStream in = new FileInputStream(realPath); // 文件输入流
int len = 0;
byte[] buffer = new byte[1024];
OutputStream out = response.getOutputStream();
while((len = in.read(buffer))>0){
out.write(buffer,0,len); // 将缓冲区的数据输出到客户端浏览器
}
in.close();
return null;
}
前端进行下载请求:
访问结果:
点击下载:
下载成功
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)