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();
}
}
