1.在页面中,可以直接通过超链接来下载:

  a) 如果浏览器能够打开该文件,那么直接在浏览器中显示---不是想要的效果

  b) 任何人都能下载,不能进行权限控制

2.通过servlet来进行下载,在servlet中是通过文件流来下载的。

@WebServlet("/download")
public class DownloadServlet extends HttpServlet{
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setCharacterEncoding("utf-8");
resp.setContentType("application/octet-stream");
//解决 以文件形式下载 而不会被浏览器打开 以及中文文件名需要编码
resp.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode("中国", "utf-8")+".txt");
PrintWriter os = resp.getWriter();
String path = this.getServletContext().getRealPath("/download");
Reader is = new BufferedReader(new FileReader(new File(path,"t.txt")));
int len=0;
char[] buffer = new char[200];
while((len=is.read(buffer))!=-1){
os.print(new String(buffer,0,len));
}
is.close();
os.close();
}
}
05-28 03:33