// 基本套路:从服务器本地硬盘地址种把文件读取出来,发送到前端
// 为便于大家学习文件下载技术,只考虑文件名是死的情况(其实可以从前端提交的参数中读取)
//设置相应头,告诉浏览器用他的默认下载程序来接收后台数据//如果不设置响应头,则浏览器是自己直接打开浏览//还要设置相应头,告诉浏览器这个下载的文件名是什么
public class Download extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 基本套路:从服务器本地硬盘地址种把文件读取出来,发送到前端
// 为便于大家学习文件下载技术,只考虑文件名是死的情况(其实可以从前端提交的参数中读取)
//设置相应头,告诉浏览器用他的默认下载程序来接收后台数据
response.setContentType("application/force-down");
//还要设置相应头,告诉浏览器这个下载的文件名是什么
String filename = "img/1.gif";
response.setHeader("Content-Disposition", "attachment;filename=\""+filename+"\"");
String path = getServletContext().getRealPath(filename);
// 流拷贝
InputStream in = new FileInputStream(new File(path));
OutputStream out = response.getOutputStream();
byte buf[] = new byte[512];
int len = 0;
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
}
out.close();
in.close();
}
}