protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {
// 1、获取文件路径
String realPath = "G:\\test.mp4";
// 2、获取文件真实名称
String realFilename = realPath.substring(realPath.lastIndexOf("\\") + 1);
System.out.println("realFilename = " + realFilename);
// 3、设置下载头部信息,包含真实名称
resp.setHeader("Content-Disposition", "attachment; filename=" + realFilename);
// 4、 获取FileInputStream
FileInputStream in = new FileInputStream(realPath);
ServletOutputStream out = resp.getOutputStream();
// 5、设置缓冲区buffer
byte[] buffer = new byte[1024];
// 6、获取输入流outputStream
int len = 0;
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
in.close();
out.close();
// 7、将输入流写入缓冲区,并输出到输入流
// 8、关闭流
}
HttpServletResponse下载文件示例
最新推荐文章于 2024-03-22 08:17:54 发布