文件下载

1、通过超链接下载

优点:实现简单

缺点:暴露服务器的文件目录造成安全隐患


	t.txt下载
	
17AJAX.docx下载

2、通过文件流实现下载

a)设置媒体文件类型(MIME)

可以在Tomcat-->conf-->web.xml中查找,查询“bin”、“com”

所以可以设置为:application/octet-stream  /   application/x-msdownload

实例:

Servlet:

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//设置媒体文件类型
		resp.setContentType("application/octet-steam");
		resp.setHeader("Content-Disposition", "attachment;filename=t.txt");
		
		String path = req.getRealPath("/download");
		File file = new File(path,"t.txt");
		
		resp.setContentLength((int)file.length());
		
		InputStream io = new FileInputStream(file);
		byte by[] = new byte[400];
		int len = 0;
		OutputStream out = null;
		while((len=io.read(by)) != -1) {
			out = resp.getOutputStream();
			out.write(by,0,len);
		}
		io.close();
		out.close();
	}

3、多文件下载

a)前台传文件名

4、文件下载的中文名处理

resp.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(filename,"utf-8")+"");

 

你可能感兴趣的:(#,初学servlet,jsp)