public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//文件在服务器的路径
String path = "";
// 查找文件
File file = new File(getServletContext().getRealPath("/") + path);
// 查找不到则返回错误
if (! file.exists()) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return ;
}
// 设置response
response.setContentType("application/x-msdownload; charset=UTF-8");
response.addHeader("content-type", "application/x-msdownload;");
response.addHeader("content-disposition", "attachment; filename="+ response.encodeURL(file.getName()));
response.setContentLength((int)file.length());
// 输出
InputStream in = new FileInputStream(file);
OutputStream out = response.getOutputStream();
try {
int length = 0;
byte[] buffer = new byte[2048];
while ((length = in.read(buffer)) != -1) {
out.write(buffer, 0, length);
}
out.flush();
} finally {
if (in != null) {
in.close();
}
}
}
个人学习笔记
Servlet实现下载功能
最新推荐文章于 2022-04-14 13:30:36 发布